Mr.zhao
Mr.zhao

Reputation: 15

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' "

Upvotes: 1

Views: 339

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

Node *T=root is illegal in a default argument because default arguments do not have access to this. You can use two overloads instead, one with a Node* parameter and one without.

void Road(char p) { Road(p, root); }
void Road(char p, Node* T);

Upvotes: 2

Related Questions