C++ 默认参数类成员

c++ default parameters class members

本文关键字:成员 参数 默认 C++      更新时间:2023-10-16
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++ 提供的默认功能

根据

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

  1. 。同样,非静态成员不得在默认参数中使用,即使它未被计算,除非它显示为 类成员访问表达式 (5.2.5) 的 ID 表达式,除非它 用于形成指向成员 (5.3.1) 的指针。[ 示例:该 以下示例中 X::mem1() 的声明格式不正确 因为没有为用作的非静态成员 X::a 提供对象 初始值设定项。
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。它可以简单地调用第二个函数,作为第二个参数传递节点根。

问题出在方法的定义中:

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;
     }
}

有两种方法。

要么使用"魔术"默认值:

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);
}

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

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

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