您的位置:首页 > 编程语言 > C语言/C++

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的标准库中的操作符重载时大量用到了这个特性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: