使用派生类C++返回基类共享指针

发布于 2025-02-12 09:25:54 字数 1216 浏览 1 评论 0原文

我有一个接口:

/*base.hpp */

class Base {
    protected:  
    Base() = default;

    public:
    Base(Base const &) = delete;
    Base &operator=(Base const &) = delete;
    Base(Base &&) = delete;
    Base &operator=(Base &&) = delete;
    virtual ~Base() = default;

    virtual void Function1() = 0;
};

此接口中也有一个函数:

std::shared_ptr<Base> **getBase**();   //this will return the instance of Base class 

由于基类中的函数是纯虚拟的,因此示例派生类如下:

#inclide "base.hpp"
class Derived : public Base
{
    public:
    Derived();
    ~Derived();            
    virtual void Function1() override;
};

在main.cpp-&gt中;有一个调用

std::shared_ptr<Base> ptr{ nullptr };
void gettheproxy() {    
    ptr = getBase(); //call to get baseclass instance   
}

getBase 方法的getBase()实现(在单独的文件getbase.cpp中)

#include "base.hpp"
#include "derived.hpp"

Derived d;
std::shared_ptr<Base> getBase()
{
    std::shared_ptr<Base> *b= &d;
    return b;
}

错误: 在初始化中不能将“基本*”转换为基础',

从派生类实现获取基类实例的正确方法是什么? 注意:由于代码依赖性,我必须遵循此类设计。

I have a an interface:

/*base.hpp */

class Base {
    protected:  
    Base() = default;

    public:
    Base(Base const &) = delete;
    Base &operator=(Base const &) = delete;
    Base(Base &&) = delete;
    Base &operator=(Base &&) = delete;
    virtual ~Base() = default;

    virtual void Function1() = 0;
};

Also there is a function in this interface:

std::shared_ptr<Base> **getBase**();   //this will return the instance of Base class 

Since function in base class is pure virtual, sample Derived class is below:

#inclide "base.hpp"
class Derived : public Base
{
    public:
    Derived();
    ~Derived();            
    virtual void Function1() override;
};

In main.cpp -> there is a call to getBase()

std::shared_ptr<Base> ptr{ nullptr };
void gettheproxy() {    
    ptr = getBase(); //call to get baseclass instance   
}

Implementation of getBase method (in separate file getBase.cpp)

#include "base.hpp"
#include "derived.hpp"

Derived d;
std::shared_ptr<Base> getBase()
{
    std::shared_ptr<Base> *b= &d;
    return b;
}

Error:
cannot convert ‘Base*’ to Base’ in initialization

What is the correct way to get base class instance from derived class implementation?
Note: I have to follow this design of classes due to code dependency.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

陌伤浅笑 2025-02-19 09:25:54

这应该做:

std::shared_ptr<Derived> d = std::make_shared<Derived>();

std::shared_ptr<Base> getBase() { return d; }

This should do:

std::shared_ptr<Derived> d = std::make_shared<Derived>();

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