C++默认参数类成员

标签 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++ 提供的默认功能

最佳答案

根据 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/

相关文章:

c# - 如何获得具有 out 参数的方法?

bash - 使用参数扩展设置默认变量 vs if/else test -z

c++ - 需要有关对象/连接池项的 RAII 设计的建议

json - 我可以使用 jq 使用 JSON 文件中的参数来过滤和修改另一个 JSON 文件吗?

c++ - 为在 OpenGL 中使用基本物理和渲染寻找一个好的形状类设计

php - 如何在 PHP 中的对象变量中执行文本连接?

java - 类类型转换不明确

java - getResourceAsStream(file) 在哪里搜索文件?

c++ - 当容器中的基本元素是 boost::tuple 时,为什么我不能使用 std::find?

c++ - 在 QStringList 中添加“符号