【发布时间】:2021-07-27 15:00:33
【问题描述】:
我是 C++ 新手,正在尝试学习如何在函数中使用可选参数。
现在我知道你可以用这样的可选参数创建一个函数:
void X_plus_Y(int x=10, y=20) {return x + y;}
int main() {
X_plus_Y(); // returns 30
X_plus_Y(20); // set x to 20 so return 40
X_plus_Y(20, 30); // x=20, y=30: return 50
return 0;
}
但我搜索了互联网并没有找到任何方法来传递这样的可选参数:
X_plus_Y(y=30); // to set only the y to 30 and return 40
有没有办法或“破解”来实现这个结果?
【问题讨论】:
-
@Jarod42 神圣标准。
-
pedantry:它们不是可选参数;您可以省略它们并获取默认值,但它们始终存在并具有值。最好不要与
std::optional等混淆。
标签: c++ function optional-parameters