使用派生类C++返回基类共享指针
我有一个接口:
/*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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该做:
This should do: