如何将基本类共享_ptr对象分配给子类
在下面的情况下,我需要从A共享指针中调用B级b级功能(FUN1) 由设置函数返回,并且同时使用了Dynamic_cast_pointer 类共享_ptr对象可以分配给base类共享_ptr,但是在编译期间我是 不允许这样做。任何人都可以建议如何实现这种行为
#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
}
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
not allowed to do so. Can anybody suggest how to achieve this behaviour
#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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这个问题是从真正的问题中删除的。
假设您不希望此示例在运行时起作用(当它是A的实例时,您正在将A的指针作为指针作为指针 - 因此您处于未定义的行为领域),问题是您没有虚拟的方法。编译器告诉您:
当您打算将指针用于基类时,您需要拥有虚拟驱动器(个人,我总是将它们用作当然)。
请参阅演示: https://godbolt.org/z/qe6jprhsa
在这里您可以看到一个修改的示例您处于未定义的行为领域...
https://godbolt.org/z/harzop946
I presume the question is cut down from the real problem.
Presuming you're not expecting this example to work at runtime (you are casting a pointer to A as a pointer to B when it's an instance of A - so you're in undefined behaviour territory), the issue is that you have no virtual methods. The compiler tells you this:
When you intend to use pointers to a base class, you need to have virtual destructors (personally I always use them as a matter of course).
See demo: https://godbolt.org/z/qe6jPrhsa
Here you can see a modified example demonstrating that you're in Undefined Behaviour territory...
https://godbolt.org/z/harzoP946