c++ - 使用类成员函数/变量初始化默认参数
问题描述
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);
}
};
推荐阅读
- google-chrome - 编写用于触发 chrome 快捷方式的 Chrome 扩展程序
- python - 循环遍历列名称熊猫的错误
- python - python dict中的列表扩展值
- javascript - 使用预签名的 url 将文件发送到 s3 存储桶会出现 403 错误 (SignatureDoesNotMatch)
- python - Python:使用匹配的“vlookup”将列添加到另一个数据框
- zoho - Zoho Deluge - 读取/获取票证附件内容
- javascript - JavaScript表单获取请求在填写时提交空值
- python - 如何使 try/except 循环直到为真
- python - PyCharm 弱警告:'来自外部范围的阴影名称'
- typescript - 将数据从测试上下文传递到 Jest 模拟的 ES6 类