如何将基本类共享_ptr对象分配给子类

发布于 2025-01-27 14:54:36 字数 739 浏览 2 评论 0原文

在下面的情况下,我需要从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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

破晓 2025-02-03 14:54:37

我认为这个问题是从真正的问题中删除的。

假设您不希望此示例在运行时起作用(当它是A的实例时,您正在将A的指针作为指针作为指针 - 因此您处于未定义的行为领域),问题是您没有虚拟的方法。编译器告诉您:

 error: 'A' is not polymorphic

当您打算将指针用于基类时,您需要拥有虚拟驱动器(个人,我总是将它们用作当然)。

请参阅演示: 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:

 error: 'A' is not polymorphic

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文