C++ 名称查找规则之 Koenig lookup


[转自: 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的标准库中的操作符重载时大量用到了这个特性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值