首页 > 解决方案 > 通过 shared_ptr 访问子类的字段

问题描述

是否可以通过访问子类实例中的字段shared_ptr?例如,下面的代码无法编译。但是,如果我只是声明一个变量Bar bar(2),那么我可以以通常的方式访问字段b,例如bar._b

#include <memory>
#include <iostream>

using namespace std;

struct Foo {};

class Bar : public Foo {
public:
    Bar(int b) : _b(b) {};
    const int _b;
};

int main() {
    shared_ptr<Foo> bbar = make_shared<Bar>(3);
    cout << bbar->_b;
    return 0;
}

标签: c++oopc++11shared-ptr

解决方案


主要问题是您使用shared_ptr<Foo>的数据类型,您不能访问_b. 有两种不同的方法可以解决这个问题,每种方法都可以在特定情况下使用:

1.使用派生类型而不是基类型

使用autoorshared_ptr<Bar>作为您的数据类型:

shared_ptr<Bar> bbar = make_shared<Bar>(3); // or use `auto`

2.多态动态转换

在使用之前转换您的数据类型:

#include <memory>
#include <iostream>

using namespace std;

struct Foo {
    virtual ~Foo() {}
};

class Bar : public Foo {
public:
    Bar(int b) : _b(b) {};
    const int _b;
};

int main() {
    shared_ptr<Foo> bbar = make_shared<Bar>(3);
    auto fbar = std::dynamic_pointer_cast<Bar>(bbar);
    cout << fbar->_b;
    return 0;
}

但在这种情况下,您需要创建Foo一个多态类型。这就是为什么我添加virtual ~Foo() {}Foo.


推荐阅读