我发现一个程序在函数原型(prototype)设计和声明中使用了不同的参数,所以我做了一个基本程序。
#include <iostream>
using namespace std;
void add(int a, int b);
int main()
{
add(3,4);
}
void add(int c, int d){
int e = c + d;
cout << e << endl;
}
我运行这个程序,它运行良好。这是否意味着在“函数原型(prototype)设计”和“函数声明”中不需要相同的参数名称?
最佳答案
是的,声明和定义中使用的参数名称不必相同。相反,参数的类型(和顺序)应该是相同的。事实上,参数名称不是必需的,尤其是在函数声明中,即使在定义中,如果不使用它们也可以省略。
(强调我的)
An identifier can optionally be provided as a parameter name; if present in a function definition ([dcl.fct.def]), it names a parameter. [ Note: In particular, parameter names are also optional in function definitions and names used for a parameter in different declarations and the definition of a function need not be the same. If a parameter name is present in a function declaration that is not a definition, it cannot be used outside of its function declarator because that is the extent of its potential scope ([basic.scope.proto]). — end note ]
和[dcl.fct]/8 :
The return type, the parameter-type-list, the ref-qualifier, the cv-qualifier-seq, and whether the function has a non-throwing exception-specification, but not the default arguments ([dcl.fct.default]) or the exception specification ([except.spec]), are part of the function type.
请注意,参数类型列表(不包括它们的名称)是函数类型的一部分。
关于c++ - 函数原型(prototype)中的不同参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39224689/