关于使用 unique_ptr 作为向量类型的问题(C++)

问题描述 投票:0回答:1

我试图理解一个 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
的类型吗?

c++ vector attributes unique-ptr
1个回答
0
投票

向量存储指向

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";
© www.soinside.com 2019 - 2024. All rights reserved.