为什么要在 C++ 函数中最后添加默认参数?

Why should default parameters be added last in C++ functions?(为什么要在 C++ 函数中最后添加默认参数?)
本文介绍了为什么要在 C++ 函数中最后添加默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

为什么要在 C++ 函数中最后添加默认参数?

Why should default parameters be added last in C++ functions?

推荐答案

为了简化语言定义并保持代码可读性.

To simplify the language definition and keep code readable.

void foo(int x = 2, int y);

要调用它并利用默认值,您需要这样的语法:

To call that and take advantage of the default value, you'd need syntax like this:

foo(, 3);

这可能让人觉得太奇怪了.另一种选择是在参数列表中指定名称:

Which was probably felt to be too weird. Another alternative is specifying names in the argument list:

foo(y : 3);

必须使用一个新符号,因为这已经意味着什么:

A new symbol would have to be used because this already means something:

foo(y = 3); // assign 3 to y and then pass y to foo.

ISO 委员会考虑并拒绝了这种命名方法,因为他们对在函数定义之外为参数名称引入新的意义感到不舒服.

The naming approach was considered and rejected by the ISO committee because they were uncomfortable with introducing a new significance to parameter names outside of the function definition.

如果您对更多 C++ 设计原理感兴趣,请阅读 The Design and Evolution ofC++ 来自 Stroustrup.

If you're interested in more C++ design rationales, read The Design and Evolution of C++ by Stroustrup.

这篇关于为什么要在 C++ 函数中最后添加默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why does C++ compilation take so long?(为什么 C++ 编译需要这么长时间?)
Why is my program slow when looping over exactly 8192 elements?(为什么我的程序在循环 8192 个元素时很慢?)
C++ performance challenge: integer to std::string conversion(C++ 性能挑战:整数到 std::string 的转换)
Fast textfile reading in c++(在 C++ 中快速读取文本文件)
Is it better to use std::memcpy() or std::copy() in terms to performance?(就性能而言,使用 std::memcpy() 或 std::copy() 更好吗?)
Does the C++ standard mandate poor performance for iostreams, or am I just dealing with a poor implementation?(C++ 标准是否要求 iostreams 性能不佳,或者我只是在处理一个糟糕的实现?)