简体   繁体   English

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

[英]c++: How do you access base class calls in multiple/multilevel inheritance from within the class?

This is the simplified code: 这是简化的代码:

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

How do you properly qualify a call to access the members of both instances of the subclass a, the things I've tried leads to a 'a is an ambiguous base of d' error. 您如何正确地限定访问子类a的两个实例的成员的调用,我尝试过的事情导致出现“ a是d的歧义”错误。 Same question if the hierarchy was one more class deep or if a class template was involved. 相同的问题是层次结构是否更深一层类或是否包含类模板。 I'm not looking for a virtual base. 我不是在寻找虚拟基地。

You can call the immediate base class functions using the explicit calls. 您可以使用显式调用来调用直接基类函数。

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

You can call a::func from b::func similarly. 您可以类似地从b::func调用a::func

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

If you also want to access the member a::var and call a::func directly from d::d1 , you can use: 如果您还想访问成员a::var并直接从d::d1调用a::func ,则可以使用:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 c ++:通过多级继承从模板子类调用基类的模板方法 - c++: Calling a template method of a base class from a template child class though multilevel inheritance C ++多重继承和访问说明符:从基类及其派生继承 - C++ multiple inheritance and access specifiers: inherit from a base class and its derived C ++多重继承,其基类派生自同一个类 - C++ multiple inheritance with base classes deriving from the same class 具有专有基类的C ++多重继承 - C++ Multiple Inheritance With Proprietary Base Class 从C++中具有多重继承的类派生的类:派生类试图调用根基类构造函数 - Class derived from a class with multiple inheritance in C++: the derived class is trying to call the root base class constructor 你如何为继承的c ++类编写一个c包装器 - how do you write a c wrapper for a c++ class with inheritance 从C ++中的空基类继承 - Inheritance from empty base class in C++ 如何在 C++ 上的多个 inheritance 上下文中使用来自特定基 class 的运算符 - How to use an operator from a specific base class on multiple inheritance context on C++ 如何从派生的类实例调用模板化的基类函数 - c++ How do you call a templated base-class function from derived class instance 在C ++中进行n次继承后停止从基类继承 - Stopping inheritance from base class after nth inheritance in C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM