如果没有调用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]
而且我知道我不应该首先创建这样的明确性,但是在某些其他代码中可能会遇到这种情况,并且我在不改变函数或类定义的情况下询问是否有一种方法可以解决这个问题。
答案 0 :(得分:3)
您应该使用精心设计的类型说明符:
class test an_instance_of_test;
正如标准所说(§3.4.4):
elaborated-type-specifier (7.1.6.3)可用于引用先前声明的 class-name 或 enum-name 即使名称已被非类型声明隐藏。
名称查找只会忽略任何非类型的名称:
根据3.4.1查找标识符,但忽略已声明的任何非类型名称。