开发者

About C++ types, and vectors

开发者 https://www.devze.com 2023-03-29 04:42 出处:网络
Let\'s say I have a few classes Class Alpha (Base Class) Class Beta (Subclass Alpha) Class Delta (Subclass Alpha)

Let's say I have a few classes

Class Alpha (Base Class)

Class Beta (Subclass Alpha)

Class Delta (Subclass Alpha)

Would it be possible to create a vector<Alpha> and store object instances of types Alpha, Beta, and 开发者_如何学CDelta all within that vector, and have the vector function as normal?

If not, supposing I wanted to have some sort of functionality like that, what would be the best approach?


One approach to this is to have a vector full of pointers, and have the functions that are common to each of them be virtual in the base class:

class Alpha {
public:
    virtual void dosomething() { /* do something as an alpha */ }
};

class Beta : public Alpha {
public:
    void dosomething() { /* do something as a beta */ }
};

class Delta : public Alpha {
public:
    void dosomething() { /* do something as a delta */ }
};

vector<Alpha*> v;
v.push_back(new Alpha);
v.push_back(new Beta);
v.push_back(new Delta);

v[1]->dosomething(); // calls Beta's dosomething

You have to be careful with this approach however, to make sure and delete everything you new to put into the container. You could use smart pointers and avoid this caveat though:

vector<shared_ptr<Alpha> > v;
v.push_back(shared_ptr<Alpha>(new Alpha));
v.push_back(shared_ptr<Alpha>(new Beta));
v.push_back(shared_ptr<Alpha>(new Delta));

v[1]->dosomething(); // still calls Beta's dosomething

The reason you don't want to have a vector of Alphas (instead of Alpha*s, which are alright) is because STL containers copy the values you give them, and if you copy a Beta (or Delta) as an Alpha, only Alpha's copy constructor will be called and the resulting information will have to fit into the size of an Alpha (which if you've added any information to the subclass it won't be big enough), and the extra information the Beta (or Delta) had is lost. This is called slicing.


The best way would be to store smart pointers to the classes in the vector.

You cannot pass by value, as you then get slicing.

If you pass by reference, you could have variables going out of scope.

std::vector<shared_ptr<Alpha> > blah;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号