c ++默认参数类成员

时间:2015-01-09 18:22:34

标签: c++ class parameters default members

class bst
{
private:

typedef struct nod
{
  int data;
  nod* left;
  nod* right;
  nod(int key):data(key),left(NULL),right(NULL){}
}node;
 node* root;

public:

void create();
void add(int key,node*curr=root);
void c2ll();
void print(){}

代码无法编译...... 我得到以下错误。

ain.cpp: In function ‘int main()’:
main.cpp:7:12: error: call to ‘void bst::add(int, bst::node*)’ uses the default argument for parameter 2, which is not yet defined
   bt.add(50);
            ^
In file included from bst.cpp:1:0:
bst.h:14:8: error: invalid use of non-static data member ‘bst::root’
  node* root;
        ^
bst.h:19:28: error: from this location
 void add(int key,node*curr=root);
                            ^
bst.h:14:8: error: invalid use of non-static data member ‘bst::root’
  node* root;
        ^
bst.cpp:10:34: error: from this location
 void bst::add(int key,node* curr=root)

欢迎提出任何建议......我试图避免编写包装器方法,而是使用c ++提供的默认功能

4 个答案:

答案 0 :(得分:4)

问题在于方法的定义:

void add(int key,node*curr=root);

root未在您使用它的上下文中定义。如果您指的是成员变量node* root,则无法在成员函数中默认使用成员变量,但您可以将NULL(0)设置为默认值并在定义中进行检查。

void bst::add ( int key,node*curr=NULL)
{
     if(curr==NULL) {
         curr= this->root;
     }
}

答案 1 :(得分:3)

根据C ++标准(8.3.6默认参数)

  
      
  1. ...同样,非静态成员不得在默认参数中使用,即使它未被评估,除非它显示为   类成员访问表达式(5.2.5)的id-expression或除非它   用于形成指向成员的指针(5.3.1)。 [例子:   以下示例中的X :: mem1()声明格式错误   因为没有为非静态成员X :: a提供对象   初始化程序。
  2.   
int b;
class X {
int a;
int mem1(int i = a); // error: non-static member a
// used as default argument
int mem2(int i = b); // OK; use X::b
static int b;
};

您可以重载函数add。例如

void add( int key );

void add( int key, node *curr );

默认情况下,第一个函数将使用root。它可以简单地调用第二个函数作为第二个参数传递给节点根。

答案 2 :(得分:2)

有两种方式。

使用“魔法”默认值:

void add(int key, node* curr = NULL)
{
    if (curr == NULL)
        curr = root;
    // ...
}

或完全抛弃默认值并使用重载:

void add(int key, node* curr)
{
    // ...
}

void add(int key)
{
    add(key, root);
}

我的个人偏好是后者,但你根本不应该在树的界面中公开节点类型,因为这会让树的用户破坏它的平衡。

答案 3 :(得分:0)

像这样使用: const node* root = NULL; void add(int key,node*curr=root);

您可以在此处查看实际运行示例: http://ideone.com/tJ1r29