[英]How to assign base class shared_ptr object to child class shared_ptr object
in below scenario, I need to invoke child class B function (fun1) from Base class A shared pointer returned by setup function and for the same have used dynamic_cast_pointer so that derived class shared_ptr object can be assigned to Base class shared_ptr but during compilation I am不允許這樣做。 誰能建議如何實現這種行為
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
void fun() {cout<<"A"<<endl;}
};
class B : public A
{
public:
void fun1() {cout<<"B" <<endl;}
};
shared_ptr<A> setup(shared_ptr<A> ptr = nullptr )
{
if(!ptr)
{
ptr = make_shared<A> ();
}
ptr.get()->fun();
return ptr;
}
int main() {
auto ptr = std::dynamic_pointer_cast <B> (setup());
ptr->fun1(); // Doesn't compile
}
我認為這個問題是從真正的問題中刪除的。
假設您不希望此示例在運行時工作(當它是 A 的實例時,您將指向 A 的指針轉換為指向 B 的指針 - 所以您處於未定義的行為區域),問題是您沒有虛擬方法。 編譯器告訴你:
error: 'A' is not polymorphic
當您打算使用指向基址 class 的指針時,您需要有虛擬析構函數(我個人總是理所當然地使用它們)。
見演示: https://godbolt.org/z/qe6jPrhsa
在這里你可以看到一個修改過的例子,證明你在未定義的行為領域...... https://godbolt.org/z/harzoP946
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.