函数参数前的class关键字是什么?
问题描述:
为什么此代码有效?在 f
函数参数上看到前面的 class
关键字?
Why does this code work? See the class
keyword in front on the f
function argument? What does it change if I add it?
struct A
{
int i;
};
void f(class A pA) // why 'class' here?
{
cout << pA.i << endl;
}
int main()
{
A obj{7};
f(obj);
return 0;
}
答
如果是函数或变量在作用域中存在的名称与类类型的名称相同,可以在类名之前添加类别以消除歧义,从而导致详细的类型说明符。
If a function or a variable exists in scope with the name identical to the name of a class type, class can be prepended to the name for disambiguation, resulting in an elaborated type specifier.
始终允许您使用详细的类型说明符。但是,它的主要用例是当您拥有一个具有相同名称的函数或变量时。
You are always allowed to use an elaborated type specifier. Its major use case, however, is when you have a function or variable with an identical name.
cppreference.com中的示例:
Example from cppreference.com:
class T {
public:
class U;
private:
int U;
};
int main()
{
int T;
T t; // error: the local variable T is found
class T t; // OK: finds ::T, the local variable T is ignored
T::U* u; // error: lookup of T::U finds the private data member
class T::U* u; // OK: the data member is ignored
}