使用 class 成员 function/variable 初始化默认参数

initializing default parameter with class member function/variable

class C {
private:
     int n{ 5 };

public:
    int return5() { return 5; }
    void f(int d = return5()) {

    }

    void ff(int d = n) {

    }


};

为什么我不能用成员 class 初始化函数默认参数?我得到一个错误:非静态成员引用必须相对于特定对象。

我认为问题是因为还没有实例化对象,但是有什么方法可以做到吗?

默认参数被认为是从调用方上下文中提供的。它只是不知道可以调用 non-static 成员函数 return5 的对象。

您可以使 return5 成为 static 成员函数,它不需要调用对象。例如

class C {
    ...
    static int return5() { return 5; }
    void f(int d = return5()) {
    }
    ...
};

或者创建另一个重载函数为

class C {
private:
     int n{ 5 };
public:
    int return5() { return 5; }
    void f(int d) {
    }
    void f() {
        f(return5());
    }
    void ff(int d) {
    }
    void ff() {
        ff(n);
    }
};