vendredi 13 novembre 2020

C++ [Error] invalid use of non-static data member 'Tree::root'

#include<iostream>
using namespace std;
class Node{
    public:
        Node *lch,*rch;
        char data;
        Node(char data){
             this->data=data;
             this->lch=nullptr;
             this->rch=nullptr;
       }
};

class Tree{
    private:
        Node *root;
    public:
        Tree(){
            root=nullptr;
        }
        void Road(char p,Node *T=root);

    public:
        void init(Node* &T=root){
            char data;
            cin>>data;
            if(data!='#'){
                T=new Node(data);
                init(T->lch);
                init(T->rch);
            }
        }
};
void Tree::Road(char p,Node *T){
    if(!T) return;
    Road(p,T->lch);
    Road(p,T->rch);
    if(T->data==p){
        cout<<T->data<<"\t";
        p=T->data;
    }
}

int main(){
    Tree T;
    T.init();
    T.Road('A');
    return 0;
}

In class Tree, if I use "static Node* root", It would work well. So why I must add "static"? And when I used "static Node* root",I got an new error that " test.cpp :(.rdata$.refptr._ZN4Tree4rootE[.refptr._ZN4Tree4rootE]+0x0): undefined reference to `Tree::root' "

Aucun commentaire:

Enregistrer un commentaire