为什么我不能使用 using 来消除基本成员变量之间的歧义?

Why can't I use using to disambiguate between base members variables?

本文关键字:变量 成员 之间 歧义 不能 using 为什么      更新时间:2023-10-16

在这个简单的类层次结构中,我试图让类C通过告诉它"使用B::x"来消除使用哪个x的歧义,但这在g++中无法编译,因为它仍然无法找出我在函数foo中指的是哪个x。我知道使用可以用来促进隐藏的方法,但为什么不变量?我考虑过将类X作为a和B的虚基并定义X,但这并不是我想要的;我想要的是A:x被直接从它派生的东西使用,除了从B派生的东西,有点像Python使用其成员(name)解析顺序算法的方式(最后一个类获胜,所以在这种情况下使用B:x,请参阅http://starship.python.net/crew/timehorse/BFS_vs_MRO.html获取描述。)

我在评估ISO c++ 2011在这方面的不足是正确的吗?使用"using"来消除基本成员变量的歧义是不可能的?

class A {
protected:
    int x;
};
class B {
protected:
    int x;
};
class C : public A, public B {
protected:
    using B::x;
public:
    int foo(void) { return x; }
};

编辑:编译器版本:g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

在c++ 11和c++ 4.8下运行良好:http://ideone.com/oF4ozq

#include <iostream>
using namespace std;
class A {
protected:
    int x = 5 ;
};
class B {
protected:
    int x = 42 ;
};
class C : public A, public B {
protected:
    using B::x;
public:
    int foo(void) { return x; }
    int fooa(void) { return A::x; }
     int foob(void) { return B::x; }
};
int main() {
    C c;
    std::cout<<c.foo()<<std::endl;
    std::cout<<c.fooa()<<std::endl;
    std::cout<<c.foob()<<std::endl;
    return 0;
}