C++ 函数参数前的class关键字是什么?
为什么这个代码可以工作?请参见C++ 函数参数前的class关键字是什么?,c++,c++11,C++,C++11,为什么这个代码可以工作?请参见f函数参数前面的class关键字?如果我添加它,它会发生什么变化 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; } 结构A { int i; }; void f(A类pA)//为什么在这里
f
函数参数前面的class
关键字?如果我添加它,它会发生什么变化
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;
}
结构A
{
int i;
};
void f(A类pA)//为什么在这里使用“class”?
{
cout如果作用域中存在一个函数或变量,其名称与类类型的名称相同,则可以在名称前面加上类以消除歧义,从而导致错误 您总是可以使用精心设计的类型说明符。然而,它的主要用途是当您有一个具有相同名称的函数或变量时 来自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
}
因此这里的
类
与类型名
相同?@Narek:No。在本例中(或在您的示例中)尝试使用类型名
你会发现它失败了。这个答案的措辞有点不正确。你总是可以使用精心设计的类型说明符。但是,它的主要用途是当你有一个同名的函数或变量时。@Christian Hackl;强调得很好。我做了相应的更新。