是否可以通過訪問子類實體中的欄位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;
}
uj5u.com熱心網友回復:
主要問題是您正在使用shared_ptr<Foo>
作為您的資料型別,您是否無法訪問_b
. 有兩種不同的方法可以解決這個問題,每種方法都可以在特定情況下使用:
1. 使用派生型別而不是基型別
使用auto
或shared_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
.
uj5u.com熱心網友回復:
您的代碼的問題在于基類 ( Foo
) 不繼承派生類 ( Bar
)的資料成員。如果要通過基類訪問派生類資料成員,則需要使用虛函式來執行此操作。
#include <memory>
#include <iostream>
using namespace std;
class Foo {
public:
virtual int val() = 0; // pure virtual function that needs to be overridden
};
class Bar : public Foo {
public:
Bar(int b) : _b(b) {};
const int _b;
virtual int val() { return _b; }
};
int main() {
shared_ptr<Foo> bbar = make_shared<Bar>(3);
cout << bbar->val();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368061.html