成员 属性 作为方法的默认值

Member property as default value for method

我有一个如下所示的头文件

#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H

struct Node
{
  int data;
  Node *left, *right;
  Node(int data);
};

class BinarySearchTree
{
  Node *head;
 public:
  BinarySearchTree();
  void insert(int data);
  void inorder(Node *cur = head);
};

#endif

它说

In file included from Binary_Search_Tree.cpp:2:0:
Binary_Search_Tree.h:17:28: error: invalid use of non-static data member ‘BinarySearchTree::head’
   void inorder(Node *cur = head);
                            ^
Binary_Search_Tree.h:13:9: note: declared here
   Node *head;

注意:我在定义方法时没有提供默认值。我想那是没有必要的。

默认值只允许静态或常量值?如果是,那为什么? 或者其他什么地方不对?

您正在寻找的行为无法在 C++ 中完成。默认值必须是 "somewhat constant"。这意味着实际常量或静态字段等。有更多信息 here 关于允许的内容而不是默认参数。


解决此问题的一种方法是不带任何参数的重载仅调用从 head 开始的 one-argument 函数。 另一种是使用 null 作为默认参数,并在提供时用 head 替换它。不过,如果您到达空叶节点,这可能会中断。

引自标准(草案):

A non-static member shall not appear in a default argument unless it appears as the id-expression of a class member access expression ([expr.ref]) or unless it is used to form a pointer to member ([expr.unary.op])


Note: I've not provided the default value while defining the method. I guess that isn't necessary.

甚至不允许在重新声明中重新定义默认参数(这是对先前声明函数的定义)。

Only static or constant values are allowed for default values ?

没有。 Non-constant 值也是允许的。但也有很多例外,成员都在例外之内。


您可以通过使用重载来解决该限制。