gpt4 book ai didi

c++ - 在函数中使用非静态值作为默认参数

转载 作者:太空狗 更新时间:2023-10-29 21:31:49 27 4
gpt4 key购买 nike

有没有一种很好的方法可以将非静态值作为函数中的默认参数?我见过一些对同一个问题的较早的回答,这些回答总是以显式写出重载而告终。这在 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 小节描述了成员访问(摘录):

A non-static member shall not appear in a default argument unless it appears as the id-expressionof a class member access expression (8.5.1.5) or unless it is used to form a pointer to member (8.5.2.1).[Example:The declaration of X::mem1()in the following example is ill-formed because no object is supplied for the non-static memberX::a used as an initializer.

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;
};

关于c++ - 在函数中使用非静态值作为默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57125504/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com