从派生类中引用基类成员 [英] Refer base class members from derived class

查看:196
本文介绍了从派生类中引用基类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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; }

这篇关于从派生类中引用基类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆