函数参数之前的类关键字是什么

What is the class keyword before a function argument?

本文关键字:关键字 是什么 参数 函数      更新时间:2023-10-16

为什么这段代码有效?看到 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;
}

如果作用域中存在名称与类类型名称相同的函数或变量,则可以在名称前面加上类以消除歧义,从而生成详细的类型说明符。

始终允许您使用详细的类型说明符。但是,它的主要用例是当您有一个具有相同名称的函数或变量时。

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
}