从派生类中引用基类成员
问题描述:
class A {
public:
void fa() {
}
};
class B : public A{
public:
void fb() {
}
};
class C : public A, public B {
public:
void fc() {
//call A::fa(), not B::A::fa();
}
};
如何调用 A :: fa()
从 C :: fc()
函数。
GCC使用直接基础警告C由于模糊性而无法访问
,这是否意味着没有直接的方法引用基类成员?
GCC warns withdirect base A inaccessible in C due to ambiguity
, does this mean there is no direct way to refer base class members?
答
一个选项是创建一个存根类,子对象:
One option would be to create a stub class that you can use for casting to the right base class subobject:
struct A {
void fa() { }
};
struct B : A {
void fb() { }
};
// Use a stub class that we can cast through:
struct A_ : A { };
struct C : A_, B {
void fc() {
implicit_cast<A_&>(*this).fa();
}
};
其中 implicit_cast
定义为:
template <typename T> struct identity { typedef T type; }
template <typename T>
T implicit_cast(typename identity<T>::type& x) { return x; }