使用类函数中的类数据成员作为默认值 c++

Using a class data-member in a class function as default value, c++

本文关键字:默认值 c++ 数据成员 类函数      更新时间:2023-10-16

在 c++ 中,我试图将类数据设置为类中函数的默认值,但它在构建它时抛出了一个错误。代码如下所示:

    class tree{
    public:
    node *root;
    bool push(node what, node* current = root, int actualheight = 1){

编译器引发错误

从函数位置无效使用非静态数据成员"tree::root"

如果我删除"当前"的默认值,它可以正常工作。可能是什么问题?我该如何解决它?

函数参数列表中没有this指针,因此不能在默认参数中引用类成员。

解决方案是重载函数:

bool push(node what, node* current, int actualheight = 1){...}
bool push(node what){ return push(what, root); }

现在,当您使用一个参数调用push时,它会转发到另一个重载,提供root作为第二个参数,这完全符合您想要实现的目标。