我有一个接口:
/*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;
};
In main.cpp ->有一个调用getBase()
std::shared_ptr<Base> ptr{ nullptr };
void gettheproxy() {
ptr = getBase(); //call to get baseclass instance
}
getBase的实现方法(在单独的文件getBase.cpp中)
#include "base.hpp"
#include "derived.hpp"
Derived d;
std::shared_ptr<Base> getBase()
{
std::shared_ptr<Base> *b= &d;
return b;
}
错误:初始化时无法将' Base* '转换为' Base '
从派生类实现中获得基类实例的正确方法是什么?注意:由于代码依赖,我必须遵循这种类的设计。
应该这样做:
std::shared_ptr<Derived> d = std::make_shared<Derived>();
std::shared_ptr<Base> getBase() { return d; }