简体   繁体   中英

c++ declaring a variable of a class within that class

I have the following code:

template <typename T>
class Node{
public: 
    Node<T>(T data){
        this->data = data;
    }
    T data;
    Node<T> left; 
    Node<T> right;
};

But it doesn't like how I have member variables of the same type as the class they are in because the compiler doesn't know what "Node" is.

You want to declare left and right as Node<T> * :

Node<T> *left;
Node<T> *right;

The problem is not just that the compiler doesn't have the complete definition yet, but that you are trying to say a Node contains two other Nodes, so there is no sensible definition for the size of a Node.

Create a forwarding class declaration:

template<typename T>
class Node;

template<typename T>
class Node {
public:
   T data;
   Node<T> left, right;
   // implementation here
}

This ---> Node<T> left,right causes compiler error. To fix it, you can declare left and right to be pointers, references, or static nodes:

template<typename T>
class Node {
public:
    Node(T data) : data(data){}
    T data;
    Node<T> *left, *right; // Ok
              /* OR */
    Node<T> &left, &right; // Ok
              /* OR */
    static Node<T> left, Node<T> right; // also Ok

    Node<T> left, right; // No way, causes error

};

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