本文介绍了将派生类对象存储在基类变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个向量中存储几个类的实例。因为所有类都继承自同一个基类,所以应该是可能的。

I would like to store instances of several classes in a vector. Since all classes inherit from the same base class this should be possible.

想象下这个程序:

#include <iostream>
#include <vector>
using namespace std;

class Base
{
    public:
    virtual void identify ()
    {
        cout << "BASE" << endl;
    }
};

class Derived: public Base
{
    public:
    virtual void identify ()
    {
        cout << "DERIVED" << endl;
    }
};

int main ()
{
    Derived derived;

    vector<Base> vect;
    vect.push_back(derived);

    vect[0].identify();
    return 0;
}



我希望它打印DERIVED,因为识别方法虚拟。相反,'vect [0]'似乎是一个基本的实例,它打印

I expected it to print "DERIVED", because the "identify" method is virtual. Instead 'vect[0]' seems to be a 'Base' instance and it prints

我想我可以写自己的容器(可能从向量派生)不知何故,能够做到这一点(也许只持有指针...)。我只是想问,如果有更多的C ++ ish方法这样做。我想完全向量兼容(只是为了方便,如果其他用户应该使用我的代码)。

I guess I could write my own container (probably derived from vector) somehow that is capable of doing this (maybe holding only pointers...). I just wanted to ask if there is a more C++ish method for doing this. AND I would like to be completely vector-compatible (just for convenience if other users should ever use my code).

推荐答案

您会看到

您正在存储对象在一个向量中的派生类,它应该存储Base类的对象,这导致对象切片,并且存储的对象的派生类特定成员被切分,因此存储在向量中的对象只是作为Base类的对象。

What you are seeing is Object Slicing.
You are storing object of Derived class in an vector which is supposed to store objects of Base class, this leads to Object slicing and the derived class specific members of the object being stored get sliced off, thus the object stored in the vector just acts as object of Base class.

解决方案:

您应该将指向Base类的对象的指针存储在向量:

You should store pointer to object of Base class in the vector:

vector<Base*>



通过存储一个指向Base类的指针,就不会有切片,你可以实现所需的多态行为

由于你要求一个 C ++ ish 这样做,正确的方法是使用一个合适的 ,而不是在向量中存储原始指针。这将确保您不必手动管理内存, 会为您执行此操作自动。

By storing a pointer to Base class there would be no slicing and you can achieve the desired polymorphic behavior as well.
Since you ask for a C++ish way of doing this, the right approach is to use a suitable Smart pointer instead of storing a raw pointer in the vector. That will ensure you do not have to manually manage the memory, RAII will do that for you automatically.

这篇关于将派生类对象存储在基类变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:12