读书人

用到成员变量的递归成员函数,该如何处

发布时间: 2012-02-23 22:01:34 作者: rapoo

用到成员变量的递归成员函数

C/C++ code
class sortTree {    Tnode* root;    int cnt;public:    sortTree(): root(NULL),cnt(-1) {        cout<<root<<endl<<cnt<<endl;    }    sortTree(string wd) {        Tnode* p=new Tnode;        p->count=0;        ++cnt;        p->word=wd;        p->left=NULL;        p->right=NULL;    }    ~sortTree() {}    //add    void print(Tnode* root1=root) {  //这个成员递归函数,需要用到成员变量root,请问如何实现??不慎感激!!!        if (NULL!=root1) {            if (NULL!=root1->left)                print(root1->left);            cout<<"No. "<<root1->count<<" : "<<root1->word<<endl;            if (NULL!=root1->right)                print(root1->right);        }    }};


是查找树的中序遍历,调试通过给分!!

[解决办法]
CSS code
void print(Tnode* root1)使用的时候把root传进来就行
[解决办法]
C/C++ code
#include <iostream>#include <string>using namespace std;class Tnode{    public:            int count;            string word;            Tnode* left;            Tnode* right;            Tnode():count(0),word(""),left(NULL),right(NULL){}            Tnode(string w):count(0),word(w),left(NULL),right(NULL){}};            class sortTree {  private:            int cnt;public:       Tnode *root;    sortTree():root(NULL),cnt(-1)    {        cout<<root<<endl<<cnt<<endl;    }        sortTree(string wd) {        root=new Tnode(wd);        root->count=0;        ++cnt;        root->word=wd;        root->left=NULL;        root->right=NULL;    }    ~sortTree() {}    //add    void print(Tnode* root) {  //这个成员递归函数,需要用到成员变量root,请问如何实现??不慎感激!!!        if (NULL!=root) {            if (NULL!=root->left)                print(root->left);            cout<<"No. "<<root->count<<" : "<<root->word<<endl;            if (NULL!=root->right)                print(root->right);        }    }};int main(){     sortTree s1("s1"),s2("s1left"),s3("s1right");     s1.root->left = s2.root;     s1.root->right = s3.root;     s1.print(s1.root);     system("pause");}
[解决办法]
C/C++ code
    void print(Tnode* root) {  //这个成员递归函数,需要用到成员变量root,请问如何实现??不慎感激!!!        if (NULL!=root) {            if (NULL!=root->left)                print(root->left);            cout<<"No. "<<root->count<<" : "<<root->word<<endl;            if (NULL!=root->right)                print(root->right);        }    }void printTree(){  //驱动函数print(root);}
[解决办法]
把第一个函数变成私有就好了

读书人网 >C++

热点推荐