为什么 C++ 允许未命名的函数参数?

Why does C++ allow unnamed function parameters?(为什么 C++ 允许未命名的函数参数?)
本文介绍了为什么 C++ 允许未命名的函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

以下是完全合法的C++代码

void foo (int) {
    cout << "Yo!" << endl;
}

int main (int argc, char const *argv[]) {
    foo(5); 
    return 0;
}

我想知道,考虑到无法从函数内部引用它们,是否存在将未命名参数留在函数中的值.

I wonder, if there a value to ever leave unnamed parameters in functions, given the fact that they can't be referenced from within the function.

为什么这首先是合法的?

Why is this legal to begin with?

推荐答案

是的,这是合法的.这对于在不打算使用相应参数的实现中从基类实现虚拟非常有用:您必须声明参数以匹配基类中的虚拟函数的签名,但您不打算使用它,所以你不用指定名称.

Yes, this is legal. This is useful for implementations of virtuals from the base class in implementations that do not intend on using the corresponding parameter: you must declare the parameter to match the signature of the virtual function in the base class, but you are not planning to use it, so you do not specify the name.

另一种常见情况是当您向某个库提供回调时,您必须符合该库已建立的签名(谢谢,Aasmund Eldhuset 提出这个问题.

The other common case is when you provide a callback to some library, and you must conform to a signature that the library has established (thanks, Aasmund Eldhuset for bringing this up).

还有一个特殊情况 定义您自己的后递增和后递减运算符:它们必须具有带有 int 参数的签名,但该参数始终未使用.不过,这种约定接近于语言设计中的一种黑客行为.

There is also a special case for defining your own post-increment and post-decrement operators: they must have a signature with an int parameter, but that parameter is always unused. This convention is bordering on a hack in the language design, though.

这篇关于为什么 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 性能不佳,或者我只是在处理一个糟糕的实现?)