为什么这段代码有效?请参阅class
前面的关键字f
函数参数?如果我添加它会改变什么?
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;
}
如果作用域中存在名称与类类型名称相同的函数或变量,则可以在名称前面添加 class 以消除歧义,从而产生详细类型说明符 http://en.cppreference.com/w/cpp/language/elaborated_type_specifier.
您始终可以使用详细的类型说明符。然而,它的主要用例是当您有一个具有相同名称的函数或变量时。
来自 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)