c++ - 通过 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;
}
解决方案
主要问题是您使用shared_ptr<Foo>
的数据类型,您不能访问_b
. 有两种不同的方法可以解决这个问题,每种方法都可以在特定情况下使用:
1.使用派生类型而不是基类型
使用auto
orshared_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
.
推荐阅读
- c++ - 即使在 if 语句中我初始化了变量,我仍然收到错误“未初始化的局部变量 '_'used”
- r - 用虚拟图替换 ggplots 列表中的 NA
- emeditor - 如何静默升级 EmEditor
- powershell - 使用 Powershell 从目录中提取和格式化文件名
- flutter - 禁止键盘箭头在颤动中输入floatingActionButton
- vbscript - MsgBox 错误:调用子代码时不能使用括号:800A0414
- mustache - 关于 mustache.js 和 turbo360 的未来
- android - Google Cloud Storage API 和 Google Drive API 有什么区别?
- intellij-idea - JetBrain 的“TODO”突出显示不起作用
- rust - 将 TCP 连接转发到另一台服务器