为什么C ++允许使用未命名的函数参数? [英] Why does C++ allow unnamed function parameters?

查看:316
本文介绍了为什么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.

另一种常见情况是您提供对某个库的回调,并且您必须遵循该库已建立的签名(感谢

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆