函数参数前的class关键字是什么? [英] What is the class keyword before a function argument?

查看:119
本文介绍了函数参数前的class关键字是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码有效?在 f 函数参数上看到前面的 class 关键字?

Why does this code work? See the class keyword in front on the f function argument? What does it change if I add it?

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;
}


推荐答案

如果是函数或变量在作用域中存在的名称与类类型的名称相同,可以在类名之前添加类别以消除歧义,从而导致详细的类型说明符

If a function or a variable exists in scope with the name identical to the name of a class type, class can be prepended to the name for disambiguation, resulting in an elaborated type specifier.

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

You are always allowed to use an elaborated type specifier. Its major use case, however, is when you have a function or variable with an identical name.

cppreference.com中的示例:

Example from 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
}

这篇关于函数参数前的class关键字是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆