当尝试在boost :: smart_ptr中以多态方式返回对象时,有人可以帮我解决以下错误:
1>C:\Program Files\Boost\boost_1_54_0\boost/smart_ptr/shared_ptr.hpp(352): error : a value of type "PBO *" cannot be used to initialize an entity of type "O*"
1> explicit shared_ptr( Y * p ): px( p ), pn() // Y must be complete
这是代码,第一种方法是发生错误的地方。 是因为我缺少复制构造函数或赋值运算符而boost :: shared_ptr需要定义那些,因此“完成”??
CE.cpp
#include "CE.h"
boost::shared_ptr<OB> CE::getObject(){
//THIS IS WHERE THE ABOVE ERROR OCCURS
return boost::shared_ptr<OB>(new PBO);
}
CE.h
#include "E.h"
#include "PBO.h"
#include <boost\shared_ptr.hpp>
#include <unordered_map>
class CE: public E{
public:
virtual boost::shared_ptr<OB> getObject();
private:
};
E.h
#include "OB.h"
#include <boost\shared_ptr.hpp>
#include <unordered_map>
class E{
public:
virtual boost::shared_ptr<OB> getObject() = 0;
private:
};
OB.h
//The parent class in the polymorphic hierarchy:
class OB{
public:
OB();
virtual void c(boost::shared_ptr<OD> lo);
virtual void d(std::unordered_map<double, long> a, std::set<double> b, boost::shared_ptr<OD> o) = 0;
protected:
};
PBO.h
#include "OD.h"
#include "OB.h"
//The child class in the polymorphic hierarchy:
class PBO : public OB{
public:
PBO();
virtual void c(boost::shared_ptr<OD> l);
private:
virtual void d(std::unordered_map<double, long> a, std::set<double> b, boost::shared_ptr<OD> c);
};
答案 0 :(得分:1)
根据错误函数boost::shared_ptr<OB> CE::getObject()
,只看到class PBO
转发声明,而不是定义。但由于必须将PBO *
转换为它的基础OB *
,因此必须看到类PBO的定义。解决方案可能是将函数声明放入标题:
class OB; // if you put this function declaration before definition of class OB
boost::shared_ptr<OB> getObject();
并实现到cpp文件中,OB
和PBO
的定义都可见:
#include "OB.h"
#include "PBO.h"
boost::shared_ptr<OB> CE::getObject(){
return boost::shared_ptr<OB>(new PBO);
}