C++ 名称查找规则之 Koenig lookup
2017-02-09 15:41
316 查看
[转自: http://saturnman.blog.163.com/blog/static/5576112010111578116/]
#include<iostream>
usingnamespace std;
namespace test_space
{
class Test
{
};
void test_func(Test&
t1,Test& t2)
{
}
void test_func(int&
t1,int& t2)
{
}
}
int main()
{
test_space::Test t1;
test_func(t1,t1);//Ok
test_func(3,3);
//Error
return0;
}
如果使用GCC编译则得到如下错误信息:
C:\Documents and Settings\saturnman\cpp>g++ name.cpp
name.cpp: In function `int main()':
name.cpp:21: error: `test_func' undeclared (first use this function)
name.cpp:21: error: (Each undeclared identifier is reported only once for each
function it appears in.)
如果使用VC++编译器则得到如下错误信息:
C:\Documents and Settings\saturnman\cpp>cl name.cpp
用于 80x86 的 Microsoft (R) 32 位 C/C++ 优化编译器 15.00.21022.08 版
版权所有(C) Microsoft Corporation。保留所有权利。
name.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: 使用了 C++ 异常处理程序,但未启用展开语义。请指定 /EHsc
name.cpp(21) : error C3861: “test_func”: 找不到标识符
C:\Documents and Settings\saturnman\cpp>
注意到错误的发生是在 test_func(3,3); 这里,而test_func(t1,t1); 却没有发生错误,这就是传说中的koenig名称查找规则,test_func(t1,t1)由参数的名字空间找到了所要调用的函数,但是由于test_func(3,3)没有参数在test_space名称空间中,所以无法找到test_fun调用这个函数,于是产生了如上的编译错误,在STL的标准库中的操作符重载时大量用到了这个特性。
#include<iostream>
usingnamespace std;
namespace test_space
{
class Test
{
};
void test_func(Test&
t1,Test& t2)
{
}
void test_func(int&
t1,int& t2)
{
}
}
int main()
{
test_space::Test t1;
test_func(t1,t1);//Ok
test_func(3,3);
//Error
return0;
}
如果使用GCC编译则得到如下错误信息:
C:\Documents and Settings\saturnman\cpp>g++ name.cpp
name.cpp: In function `int main()':
name.cpp:21: error: `test_func' undeclared (first use this function)
name.cpp:21: error: (Each undeclared identifier is reported only once for each
function it appears in.)
如果使用VC++编译器则得到如下错误信息:
C:\Documents and Settings\saturnman\cpp>cl name.cpp
用于 80x86 的 Microsoft (R) 32 位 C/C++ 优化编译器 15.00.21022.08 版
版权所有(C) Microsoft Corporation。保留所有权利。
name.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: 使用了 C++ 异常处理程序,但未启用展开语义。请指定 /EHsc
name.cpp(21) : error C3861: “test_func”: 找不到标识符
C:\Documents and Settings\saturnman\cpp>
注意到错误的发生是在 test_func(3,3); 这里,而test_func(t1,t1); 却没有发生错误,这就是传说中的koenig名称查找规则,test_func(t1,t1)由参数的名字空间找到了所要调用的函数,但是由于test_func(3,3)没有参数在test_space名称空间中,所以无法找到test_fun调用这个函数,于是产生了如上的编译错误,在STL的标准库中的操作符重载时大量用到了这个特性。
相关文章推荐
- C++ 名称查找规则之 Koenig lookup
- [C++]函数查找规则
- C++的名称查找顺序
- C++中一个容易被忽视的名字查找规则
- C++函数名称的修饰规则
- 立此存照(19)[C++]C++中的名称查找(name lookup)
- C++基本名称规则
- C++实现获取DOTA玩家名称(反汇编查找指针地址和跨进程读取war3内存)
- C++中一个容易被忽视的名字查找规则
- C++名称查找与ADL
- C/C++函数名称修饰规则及extern "C"的作用
- C++模板:名称查找
- C/C++函数名称修饰规则及extern "C"的作用(函数名压扎)
- C++中一个容易被忽视的名字查找规则
- Python LGB名称查找规则
- C++ CFileFind() 查找当前路径下所有文件夹名称
- 快速理解c++编译器名称查找规则koenig lookup(ADL)
- C 和C++ 名称修饰规则
- C++ sizeof 使用规则及陷阱分析
- 函数调用约定与函数名称修饰规则