【问题标题】:how to resolve ambiguous situation between same named function and class?如何解决同名函数和类之间的模棱两可的情况?
【发布时间】:2013-03-09 23:40:56
【问题描述】:

如果不调用 test,此代码编译没有任何问题,因此我得出结论,c++ 允许创建具有相同名称的类和函数:

class test {};
void test() {}

int main() {
  test an_instance_of_test;
}

错误是:

<stdin>: In function 'int main()':
<stdin>:5:8: error: expected ';' before 'an_instance_of_test'
<stdin>:5:27: warning: statement is a reference, not call, to function 'test' [-Waddress]

而且我知道我不应该首先创建这样的明确性,但是这可能会在其他人的代码中遇到,我想问是否有办法在不更改函数或类定义的情况下解决这个问题。

【问题讨论】:

    标签: c++ class function ambiguous


    【解决方案1】:

    您应该使用详细的类型说明符:

    class test an_instance_of_test;
    

    正如标准所说(§3.4.4):

    elaborated-type-specifier (7.1.6.3) 可用于引用先前声明的 class-nameenum-name 即使名称已被非类型声明隐藏。

    名称查找只是忽略任何非类型的名称:

    根据 3.4.1 查找标识符,但忽略任何已声明的非类型名称。

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多