c ++:如何从类中访问多级/多级继承中的基类调用?

时间:2014-05-02 22:01:35

标签: c++

这是简化的代码:

class a
{
public:
    void func( void )
    {
        //Want to call this
    }
    int avar;
};

class b : public a
{
public:
    void func( void )
    {
    }
};

class c : public a
{
public:
    void func( void )
    {
    }
};

class d : public b, public c
{
public:
    void d1()
    {
        //b::a::avar;
        //c::a::avar;
        //b::a::func();
        //c::a::func();
    }
};

你如何正确地限定一个调用来访问子类a的两个实例的成员,我尝试过的东西导致'a是一个模糊的d'错误基础。同一问题,如果层次结构是一个更深的类或是否涉及类模板。我不是在寻找虚拟基地。

1 个答案:

答案 0 :(得分:3)

您可以使用显式调用来调用直接基类函数。

void d1()
{
    b::func();
    c::func();
}

您可以同样从a::func致电b::func

class b : public a
{
public:
    void func( void )
    {
       a::func();
    }
};

如果您还想访问会员a::var并直接从a::func致电d::d1,您可以使用:

void d1()
{
    b* bPtr = this;
    bPtr->avar;        // Access the avar from the b side of the inheritance.
    bPtr->a::func();   // Call a::func() from the b side of the inheritance

    c* cPtr = this;
    cPtr->avar;        // Access the avar from the c side of the inheritance.
    cPtr->a::func();   // Call a::func() from the c side of the inheritance
}