vector of class pointers initialization

放肆的年华 提交于 2020-01-06 20:23:51

问题


    class Comp
{
    //...
};

class MyClass
{
private:
    vector<Comp*>vec;
    //...
};

I need to initialize a vector of class type pointers to objects. how can I initialize it?


回答1:


You can set an initial size (e.g. 10, as shown below), filled with all NULL values with the constructor:

vector<Comp*> vec(10, NULL);

You can also insert elements in various ways, using the push_back(), push_front(), and insert() methods.




回答2:


Use vec.push_back(new Comp()) but remember to delete all items using delete vec[<item>]




回答3:


The vector is private, I would have the constructor initialize it with the member initializer list:

class MyClass
{
public:
    MyClass();
private:
    vector<Comp*> vec;
};

MyClass::MyClass()
: vec(10, nullptr) // edit to suit the size and content.
{}                 // alternatively initialize it inside the body {} with loop


来源:https://stackoverflow.com/questions/30747539/vector-of-class-pointers-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!