问题描述
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);
}
};