C++中vector存储unique_ptr<Base>时访问派生类成员的问题
解决vector<unique_ptr >中访问派生类专属成员的问题
你遇到的问题核心是静态类型与动态类型不匹配:vec[0]的静态类型是unique_ptr<Base>,编译器只会识别Base类的成员,而deri_name是Derivate的专属成员,因此直接访问会报错。
在不修改容器类型的前提下,可以通过动态类型转换来解决:利用dynamic_cast将Base*转换为Derivate*,转换成功后就能访问派生类的专属成员。
修改后的代码示例
#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(); // 输出 "this is Derivate test by wayne" // 动态转换并访问派生类成员 if (Derivate* deri_ptr = dynamic_cast<Derivate*>(vec[0].get())) { deri_ptr->deri_name = "wong"; vec[0]->test(); // 此时会输出 "this is Derivate test by wong" } else { cout << "转换失败:当前元素不是Derivate类型" << endl; } return 0; }
关键说明
dynamic_cast仅适用于包含虚函数的类(你的代码中Base有虚函数test,满足要求),它会在运行时检查实际的动态类型。- 必须判断转换结果是否为
nullptr,如果容器中混入了其他Base的派生类对象,转换会失败,直接访问会导致未定义行为。
内容的提问来源于stack exchange,提问作者wayne wang
相关产品推荐
相关产品推荐

