gpt4 book ai didi

C++默认参数类成员

转载 作者:太空狗 更新时间:2023-10-29 23:44:35 24 4
gpt4 key购买 nike

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. ...Similarly, a non-static member shall not be used in a default argument, even if it is not evaluated, unless it appears as the id-expression of a class member access expression (5.2.5) or unless it is used to form a pointer to member (5.3.1). [ Example: the declaration of X::mem1() in the following example is ill-formed because no object is supplied for the non-static member X::a used as an initializer.
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。它可以简单地调用第二个函数作为第二个参数传递节点根。

关于C++默认参数类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27866797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com