简体   繁体   中英

How to initialize a class in C++?

I'm making a simple Binary Tree program, and I would like to initialize the left and right node. I've been trying to do it like this:

class Tree{
     Tree* left = new Tree();
     Tree* right = new Tree();
}

This is supposed to give me an accessible memory on the heap which I can use to access the left and right nodes, correct? However, it doesn't seem like that's the case. I've also tried doing this through constructors too with no luck.

Is there a way to properly initialize a class in C++? Thank you for your time.

You can create a class like this

class Tree
{
 public:
    Tree* left;
    Tree* right;
    Tree() // default constructor
    { 
        left = nullptr;
        right = nullptr;
    }
    Tree(Tree *Tleft,Tree *Tright) // parameterised constructor
    { 
        left = Tleft;
        right = Tright;
    }

    ~Tree() // Destructor
    { 
        delete left;
        delete right; 
    }
};

you can use default constructor to initialize the Tree class as nullptr , and parameterised constructor to initialize with user values, ie with Tree nodes,

void main()
{
    Tree *node1 = new Tree(); //using default constructor
    Tree *node2 = new Tree(); //using default constructor
    Tree *node3 = new Tree(node1, node2); // using parameterised constructor
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM