【问题标题】:initializing default parameter with class member function/variable使用类成员函数/变量初始化默认参数
【发布时间】:2020-08-14 04:48:02
【问题描述】:
class C {
private:
     int n{ 5 };

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

    }

    void ff(int d = n) {

    }


};

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

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

【问题讨论】:

  • 您确定要return5 而不是returnN?如您所见,return5 还不错。问题标题中暗示的void f(int d = n)...

标签: c++ parameters default-arguments


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2011-08-09
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多