对未命名的函数的参数,C ++ [英] On unnamed parameters to functions, 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.
为什么这是合法的?
推荐答案
是的,这是合法的。这对于在不打算使用相应参数的实现中从基类实现虚拟化非常有用:您必须声明该参数以匹配基类中虚拟函数的签名,但不打算使用它,因此您不需要指定名称。
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
参数的签名,但该参数始终未使用。这个约定与语言设计中的一个hack接近。
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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!