在这个简单的类层次结构中,我试图让 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 在这方面存在缺陷的评估是否正确?不可能使用“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 和 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;
}
关于c++ - 为什么我不能使用 using 来消除基本成员变量之间的歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15118454/