c++ - 将基类动态转换为派生对象

标签 c++ inheritance polymorphism dynamic-cast

我正在尝试将派生对象分配给基础对象的 vector ,然后将它们转换回派生对象。不过我无法进行类型转换制作。

struct Base
{
    string foo;
    virtual ~Base() {}
};

struct Derived : Base
{
    string bar;
};

我有一个函数可以修改基本元素的 vector 。根据某些条件,它可能会创建派生对象而不是基础对象并将其推送到 vector 上:

void foo(vector<Base> &bases)
{
    Base *base;
    if (...)
    {
        base = new Derived;
        base->foo = string("hello");
    }
    bases.push_back(*base) 
}

然后我将一个 vector 传递给该函数并尝试获取内容。

vector<Base> bases;
foo(bases);

for (auto it = bases.begin(); it != bases.end(); ++it)
{
    Base *base = &(*it);
    Derived *derived = dynamic_cast<Derived*>(base); 
    // derived == nullptr
}

我在这里错过了什么?如果我尝试访问 foo作为 Base 对象,它可以工作,但是当我尝试动态转换为 Derived 对象时,它失败了,尽管它已在 foo(vector<Base> &bases) 中创建为 Derived 对象。功能。

最佳答案

这行不通:

void foo(vector<Base> &bases)
{
    Base *base;
    if (...)
    {
        base = new Derived;
        base->foo = string("hello");
    }
    bases.push_back(*base) 
}

vector<>包含对象,而不是引用。当你push_back一个被理解为基本类型的对象,只存储适用于基本类型的数据(即“切片”)。

相反,存储一个 Base*shared_ptr<Base>vector<> .

同样值得注意的是,在上面的代码片段中,每当 if() 时,您都会遇到访问冲突。自 base 以来跳过 block 从未被初始化。

关于c++ - 将基类动态转换为派生对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28953997/

相关文章:

java - 方法覆盖特定情况

java - 为什么 java 多态性在我的示例中不起作用

class - 领域类与实现类

java - 了解扩展类和导入类之间的区别

java - 当基类被重写时,如何从另一个方法调用基类自己的方法?

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

c++ - 元编程技巧 : how to simplify implementation of two metafunctions

c++ - OPENCV如何计算特征值和特征向量?

c++ - 单列表插入到列表末尾

c++ - 使 SDL 调用纯虚成员函数作为事件回调?