c – 为什么编译器会在重载时停止名称查找?
发布时间:2020-12-16 09:52:53 所属栏目:百科 来源:网络整理
导读:我刚读过这篇文章: Fun with C++ namespaces 作者在遇到第一个时会显示编译器停止查找重载,这里使用命名空间. namespace A{ void f(int x); // like our std::sqrt(double)}namespace B{ struct S {}; // user-defined type with associated namespace B vo
我刚读过这篇文章:
Fun with C++ namespaces
作者在遇到第一个时会显示编译器停止查找重载,这里使用命名空间. namespace A { void f(int x); // like our std::sqrt(double) } namespace B { struct S {}; // user-defined type with associated namespace B void f(S); void f(int,int); void test1() { using namespace A; // using DIRECTIVE f(1); // ERROR namespace A is not considered because // B contains two overloads for 'f' f(1,2); // OK B::f(int,int) f(B::S()); // OK B::f(S) } void test2() { using A::f; // using DECLARATION f(1); // OK A::f(int) f(1,2); // ERROR A::f hides B::f(int,int) f(B::S()); // OK B::f(S) due to ADL! } } namespace C { void test3() { using namespace A; // using DIRECTIVE f(1); // OK A::f(int) f(B::S()); // OK B::f(S) due to ADL! } void test4() { using A::f; // using DECLARATION f(1); // OK A::f(int) f(B::S()); // OK B::f(S) due to ADL! } } 为什么编译器应该停止? 编辑#1:问题确实存在:为什么标准这样说? 感谢所有的答案! 解决方法
不,它不会停止“遇到第一个”,否则你找不到B :: f(int,int)和B :: f(S). 它找到给定范围内的所有重载(不仅是第一个),但是在更远的范围内不会进一步查看. 这就像C中的所有名称查找一样,如果你有一个名为var的全局变量,在某些函数中你也有一个名为var的局部变量,使用函数中的名称将引用局部变量.这样更有用,你更有可能想要使用附近声明的变量,因为它在相关的代码中. 如果有人递给你一封信,并告诉你把弗雷德放在几米远的地方,戴着一枚徽章上写着“我是弗雷德”,你会不理睬他,走到外面继续寻找世界上的每一个人叫弗雷德? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |