C++ 如何在c+中将前面的函数参数设置为其默认值+;?
如果这个基本问题已经得到回答,我表示歉意。我应该在C++ 如何在c+中将前面的函数参数设置为其默认值+;?,c++,function,parameters,default,C++,Function,Parameters,Default,如果这个基本问题已经得到回答,我表示歉意。我应该在print()的括号内放些什么,以便将第一个参数保留为默认值,但为以下参数指定新的值1和2?我知道我可以把0放进去,但有没有办法让它变成默认值 #include<iostream> using namespace std; void printer(int a=0, int b=0, int c=0){ cout << a << endl; cout << b << endl;
print()
的括号内放些什么,以便将第一个参数保留为默认值,但为以下参数指定新的值1和2?我知道我可以把0放进去,但有没有办法让它变成默认值
#include<iostream>
using namespace std;
void printer(int a=0, int b=0, int c=0){
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
int main(){
//leave a=0 and replace both b and c
printer(/*?*/,1,2);
return 0;
}
#包括
使用名称空间std;
无效打印机(int a=0,int b=0,int c=0){
不能这样做,这是不允许的。只能省略最右边的参数。默认参数列表是右关联的。因此不可能使用第一个参数列表。您可以利用函数重载来实现您想要的:
void printer(int a, int b, int c) {
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
void printer() {
printer(0, 0, 0);
}
void printer(int b = 0, int c = 0) {
printer(0, b, c);
}
int main(){
// leave a = 0 and replace both b and c
printer(1, 2);
return 0;
}
void打印机(inta、intb、intc){
cout第一个默认值之后的所有参数都是默认值。在这种特殊情况下,更改顺序可以获得所需的参数:
void printer(int b=0, int c=0,int a=0){
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
//leave a=0 and replace both b and c
printer(1,2);
void打印机(int b=0,int c=0,int a=0){
cout用于将要指定的参数委托给从返回的函数对象
您不能完全做到这一点,但解决此问题的一种方法是使用参数传递结构:
struct PrinterParams {
int a,b,c;
PrinterParams() : a(0), b(0), c(0) { }
};
void printer(int a, int b, int c) {
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
void printer(const PrinterParams ¶ms) {
printer(params.a,params.b,params.c);
}
int main(){
PrinterParams params;
params.b = 1;
params.c = 2;
printer(params);
return 0;
}
struct PrinterParams{
INTA、b、c;
PrinterParams():a(0),b(0),c(0){
};
无效打印机(int a、int b、int c){
不能这样做。任何对printer
调用的参数少于三个都是不明确的,因为两个版本都与参数列表匹配。更新了答案,请看一看。除非经常使用f
,否则这可能有点过头了!重载printer()
有什么问题吗?无效打印机(int b=0,int c=0)
并在函数中声明int a
?添加上述注释作为答案。
struct PrinterParams {
int a,b,c;
PrinterParams() : a(0), b(0), c(0) { }
};
void printer(int a, int b, int c) {
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
void printer(const PrinterParams ¶ms) {
printer(params.a,params.b,params.c);
}
int main(){
PrinterParams params;
params.b = 1;
params.c = 2;
printer(params);
return 0;
}