有没有一种好的方法可以将非静态值作为函数中的默认参数?我见过一些对同一问题的较旧的回答,这些回答总是以明确地写出超载而告终。这在 C++17 中还有必要吗?
我想做的是做类似的事情
class C {
const int N; //Initialized in constructor
void foo(int x = this->N){
//do something
}
}
而不必写
class C {
const int N; //Initialized in constructor
void foo(){
foo(N);
}
void foo(int x){
//do something
}
}
这使得重载的目的变得不那么明显。
一种相对优雅的方式(在我看来)是使用std::optional
接受参数,如果未提供参数,则使用对象的默认值:
class C {
const int N_; // Initialized in constructor
public:
C(int x) :N_(x) {}
void foo(std::optional<int> x = std::nullopt) {
std::cout << x.value_or(N_) << std::endl;
}
};
int main() {
C c(7);
c.foo();
c.foo(0);
}
您可以在标准的第 11.3.6 节中找到有关哪些内容有效/无效的完整说明。第 9 小节描述了成员访问权限(摘录):
非静态成员不得出现在默认参数中,除非
显示为类成员访问表达式的 id-表达式
(8.5.1.5) 或除非它用于形成指向成员的指针
(8.5.2.1).[示例:以下示例中 X::mem1() 的声明
格式错误,因为没有为非静态提供对象
memberX::a 用作初始值设定项。
int b;
class X {
int a;
int mem1(int i = a);// error: non-static memberaused as default argument
int mem2(int i = b);// OK; useX::b
static int b;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)