Y.Lex
Y.Lex

Reputation: 231

How to construct a tree structure with smart pointer?

Here is a code snippet which i want to get a tree structure with smart pointer.But i got c3646('parent': unknown override specifier) and c4430(missing type specifier - int assumed) in vs.Does anybody know what's going on and how do i fix it>?

#include<memory>

class Obj {
    ObjPtr parent;
};
typedef std::shared_ptr<Obj> ObjPtr;

Upvotes: 3

Views: 488

Answers (3)

alfC
alfC

Reputation: 16320

class Obj{
    public:
    using ObjPtr = std::shared_ptr<Obj>;
    private:
    ObjPtr parent;
};

doesn't need so many declarations.

Upvotes: 7

Caleth
Caleth

Reputation: 63362

You don't need a typedef at all

class Obj{
    std::shared_ptr<Obj> parent;
};

But a tree only needs owning pointers in the parent -> child direction. You can use a raw pointer in the child -> parent direction

struct Node {
    Node * parent;
    std::unique_ptr<Node> left, right;
};

Upvotes: 1

cantordust
cantordust

Reputation: 1612

Your Obj class doesn't know what an ObjPtr is because you provide the typedef after Obj. You need to place it above the class definition and provide a forward declaration of 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
};

Upvotes: 9

Related Questions