命名空间在C中发生冲突

前端之家收集整理的这篇文章主要介绍了命名空间在C中发生冲突前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法理解为什么这段代码不能编译:
namespace A {
        class F {};             // line 2
        class H : public F {};
}

namespace B {
        void F(A::H x);         // line 7
        void G(A::H x) {
                F(x);           // line 9
        }
}

我使用的是gcc 4.3.3,错误是:

s3.cpp: In function ‘void B::G(A::H)’:
s3.cpp:2: error: ‘class A::F’ is not a function,s3.cpp:7: error:   conflict with ‘void B::F(A::H)’
s3.cpp:9: error:   in call to ‘F’

我认为,因为在第9行中没有名称空间前缀,F(x)应该明确地仅表示B :: F(x).编译器尝试将x转换为自己的超类.根据我的理解,它不应该.为什么这样做?

解决方法

那是因为编译器将在其参数的相同名称空间中搜索函数.编译器找到了A :: F标识符,但它不是一个函数.结果你会得到错误.

据我所知,这是标准行为.

3.4.2 Argument-dependent name lookup
When an unqualified name is used as the postfix-expression in a function call (5.2.2),other namespaces not considered during the usual unqualified lookup (3.4.1) may be searched,and namespace-scope friend function declarations (11.4) not otherwise visible may be found. These modifications to the search depend on the types of the arguments (and for template template arguments,the namespace of the template argument).

For each argument type T in the function call,there is a set of zero or more associated namespaces and a set of zero or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of the function arguments (and the namespace of any template template argument).
Typedef names and using-declarations used to specify the types do not contribute to this set. The sets of namespaces and classes are determined in the following way…

此规则允许您编写以下代码

std::vector<int> x;
// adding some data to x
//...

// now sort it
sort( x.begin(),x.end() ); // no need to write std::sort

最后:由于Core Issue 218,一些编译器会编译有问题的代码而没有任何错误.

猜你在找的C&C++相关文章