gpt4 book ai didi

c++ - 函数参数前的类关键字是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:50:10 24 4
gpt4 key购买 nike

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

最佳答案

如果作用域中存在名称与类类型名称相同的函数或变量,则可以将类添加到名称前面以消除歧义,从而产生 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
}

关于c++ - 函数参数前的类关键字是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46139526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com