首页 > 解决方案 > 使用类成员函数/变量初始化默认参数

问题描述

class C {
private:
     int n{ 5 };

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

    }

    void ff(int d = n) {

    }


};

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

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

标签: c++parametersdefault-arguments

解决方案


默认参数被认为是从调用方上下文提供的。它只是不知道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);
    }
};

推荐阅读