提升::shared_ptr<> "explicit shared_ptr( Y * p ): px( p ), pn() // Y must be complete"

boost::shared_ptr<> "explicit shared_ptr( Y * p ): px( p ), pn() // Y must be complete"

本文关键字:shared ptr pn must be complete px lt explicit gt 提升      更新时间:2023-10-16

当我试图在boost中以多态方式返回对象时,有人能帮我解决以下错误吗::smart_ptr:

1>C:Program FilesBoostboost_1_54_0boost/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 <boostshared_ptr.hpp>
#include <unordered_map>
class CE: public E{
public:
    virtual boost::shared_ptr<OB> getObject();
private:
};

E.h

#include "OB.h"
#include <boostshared_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);
};

根据错误函数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文件中,其中OBPBO的定义都可见:

#include "OB.h"
#include "PBO.h"
boost::shared_ptr<OB> CE::getObject(){
   return boost::shared_ptr<OB>(new PBO);
}