我试图理解一个 C++ 代码,它使用存储
unique_ptr<Base>
的向量,其中Base
是一个基类并且有一个派生类Derivate
。
将
unique_ptr<Derivate>
压入这个vector时,没有错误,可以正确调用派生类的方法。
但是当尝试修改
Derivate
的特定属性时,出现错误“error: 'class Base' has no member named 'deri_name'”。
代码如下:
#include<iostream>
#include<vector>
#include <memory>
using namespace std;
class Base
{
public:
virtual void test(){
cout << "this is Base test" << endl;
}
};
class Derivate :public Base
{
public:
Derivate(const string& name):deri_name(name){
}
virtual void test(){
cout << "this is Derivate test by " << deri_name << endl;
}
string deri_name;
};
int main()
{
vector<unique_ptr<Base>> vec;
vec.push_back(make_unique<Derivate>("wayne"));
vec[0]->test(); // will sprint "this is Derivate test by wayne"
//vec[0]->deri_name = 'wong'; // will report an error " error: 'class Base' has no member named 'deri_name' "
return 0;
}
我尝试了一些方法,但似乎没有直接的方法可以将
vec[0]
从 unique_ptr<Base>
转换为 unique_ptr<Derivate>
我可以修改
vec[0]->deri_name
而不修改vec
的类型吗?
向量存储指向
Base
的指针,它没有名为 deri_name
的成员。如果你 确定 vec[0]
指向一个 Derivate
对象,你可以静态投射:
static_cast<Derivate&>(*vec[0]).deri_name = "wong";
如果你不确定,你可以动态转换:
if (auto ptr = dynamic_cast<Derivate*>(vec[0].get()))
ptr->deri_name = "wong";