1

在这个简单的类层次结构中,我试图让 C 类通过告诉它“使用 B::x”来消除使用哪个 x 的歧义,但这不能在 G++ 中编译,因为它仍然无法弄清楚我的意思是哪个 x函数 foo。我知道 using 可用于提升隐藏方法,但为什么不能使用变量?我考虑过将 X 类作为 A 和 B 的虚拟基础,并为 X 定义,但这并不是我想要的;我想要的是 A:x 直接从它派生的东西使用,除了从 B 派生时,有点像 Python 用它的成员(名称)解析顺序算法做它的方式(最后一个类获胜,所以在这种情况下 B:x使用,请参阅http://starship.python.net/crew/timehorse/BFS_vs_MRO.html了解说明。)

我对 ISO C++ 2011 在这方面存在缺陷的评估是否正确?使用“使用”来消除基本成员变量的歧义是不可能的?

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

4

1 回答 1

0

它适用于 C++11 和 g++ 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;
}
于 2014-04-15T09:32:19.607 回答