使用类成员函数/变量初始化默认参数

问题描述

class C {
private:
     int n{ 5 };

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

    }

    void ff(int d = n) {

    }


};

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

我认为是问题所在,因为尚未实例化任何对象,但是有什么方法可以做到这一点?

解决方法

默认参数被认为是从调用方上下文提供的。只是不知道可以在其上调用非静态成员函数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);
    }
};