简体   繁体   English

关于C ++类型和向量

[英]About C++ types, and vectors

Let's say I have a few classes 假设我有几节课

Class Alpha (Base Class) Alpha类(基类)

Class Beta (Subclass Alpha) Beta类(子类Alpha)

Class Delta (Subclass Alpha) Delta类(子类Alpha)

Would it be possible to create a vector<Alpha> and store object instances of types Alpha, Beta, and Delta all within that vector, and have the vector function as normal? 是否可以在该vector<Alpha>创建vector<Alpha>并存储Alpha,Beta和Delta类型的对象实例,并使向量函数正常?

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: 一种方法是使一个带有指针的向量,并使每个指针共有的函数在基类中是virtual的:

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. 但是,您必须小心这种方法,以确保并delete您要放入容器的new内容。 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 Alpha s (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. 你不想拥有Alpha的矢量(而不是Alpha* s,这是正常的)的原因是因为STL容器复制你给它们的值,如果你将Beta (或Delta )复制为Alpha ,只会调用Alpha的复制构造函数,结果信息必须符合Alpha的大小(如果你已经向子类中添加了任何信息,那么它将不够大),以及Beta的额外信息(或Delta )失去了。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM