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

Nar*_*rek 11 c++ c++11

为什么这段代码有效?请参阅函数参数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;
}
Run Code Online (Sandbox Code Playgroud)

wal*_*lly 16

如果函数或变量存在于范围内,其名称与类类型的名称相同,则可以在类之前添加类以消除歧义,从而生成详细的类型说明符.

您始终可以使用精心设计的类型说明符.但是,它的主要用例是具有相同名称的函数或变量.

来自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
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案的措辞略有错误。您*总是*允许使用详细的类型说明符。然而,它的主要“用例”是当您有一个具有相同名称的函数或变量时。 (2认同)