我正在尝试将派生对象分配给基础对象的 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/