如何解决同名函数和类之间的歧义情况

how to resolve ambiguous situation between same named function and class?

本文关键字:之间 情况 歧义 函数 何解决 解决      更新时间:2023-10-16

如果不调用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]

我知道我不应该首先创建这样的明确性,但是这可能在其他人的代码中经历过,我问是否有一种方法可以在不改变函数或类定义的情况下摆脱这种情况。

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

class test an_instance_of_test;

如标准所说(§3.4.4):

可以使用详细类型说明符(7.1.6.3)来引用先前声明的类名enum-name,即使名称已被非类型声明隐藏。

名称查找简单地忽略所有非类型的名称:

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

相关文章: