如何用智能指针构造树结构?

Y.L*_*Lex 3 c++ smart-pointers c++11

这是一个代码片段,我希望得到一个带有智能指针的树结构.但是我得到了c3646('父':未知的覆盖说明符)和c4430(缺少类型说明符 - 假设为int)在任何人都知道发生了什么我该如何修复>?

#include<memory>

class Obj {
    ObjPtr parent;
};
typedef std::shared_ptr<Obj> ObjPtr;
Run Code Online (Sandbox Code Playgroud)

can*_*ust 9

您的Obj类不知道是什么的ObjPtr是因为你提供的typedef Obj.您需要将它放在类定义之上并提供前向声明Obj:

class Obj; // Forward declaration

typedef std::shared_ptr<Obj> ObjPtr; // Now ObjPtr knows about class Obj

class Obj {
    ObjPtr parent; // We can now use ObjPtr
};
Run Code Online (Sandbox Code Playgroud)


alf*_*lfC 7

class Obj{
    public:
    using ObjPtr = std::shared_ptr<Obj>;
    private:
    ObjPtr parent;
};
Run Code Online (Sandbox Code Playgroud)

不需要这么多声明.