C++ 是否可以使用 class 变量作为默认参数

C++ is it possible to use a class variable as a default argument

我有一棵树 class,如下所示:

class avl
{
   node *root;
public:
    avl(int data){
      root->data = data;
    }

    int get_height(node *head = root){  //error here

        if (head->right == head->left) return 0;
        int l = get_height(head->left);
        int r = get_height(head->right);

        if (l > r) return l+1;
        return r+1;
     }
}

不出所料,这会在 get_height 定义处产生错误。 g++ 将其抱怨为 "invalid use of non-static data member"。我可以修改这个问题还是应该在这里使用不优雅的包装器。如果您能在标准中关于此错误原因的说明中添加一些详细信息,我将不胜感激。

不幸的是,这是不可能的。 Non-static class members 不能用作默认参数。

Non-static class members are not allowed in default arguments (even if they are not evaluated), except when used to form a pointer-to-member or in a member access expression.

int b;
class X {
  int a;
  int mem1(int i = a); // error: non-static member cannot be used
  int mem2(int i = b); // OK: lookup finds X::b, the static member
  static int b;
};

根据标准,[dcl.fct.default]/9

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]). [ 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;
};

The declaration of X​::​mem2() is meaningful, however, since no object is needed to access the static member X​::​b. Classes, objects, and members are described in [class]. — end example ]

正如您所说,您可以添加一个重载包装函数,例如

int get_height(node *head) {
    ...
}
int get_height() {
    return get_height(this->root);
}