c++多重继承(菱形方案)范例

C++ Multiple Inheritance (rhomboidal scheme) paradigm

本文关键字:方案 范例 多重继承 c++      更新时间:2023-10-16

我在多重继承菱形方案下组织了4个类。

             BASE
             /  
            /    
        Deriv1  Deriv2
                /
               /
             Final

我有每个类的"ShowXXXX()"方法(例如),其中'XXXX'是类的名称。

当我调用" ob.ShowFinal() "方法时,它打印:

  • Final的字段,
  • Deriv1的字段,
  • 基础的领域,
  • Deriv2的字段,
  • <
  • 基地的字段/gh>

问题是我想逃避第二次打印Base的字段。但是,有一个范例:因为当我调用"ob.ShowDeriv2()"时,它应该被打印:

  • Deriv2的字段,
  • <
  • 基地的字段/gh>

,当我调用" ob.ShowDeriv1() "时,它应该打印:

  • Deriv1的字段,
  • <
  • 基地的字段/gh>
我的代码:

// multipleInheritance.cpp : Defines the entry point for the console application.
//
//Summary:
//      
//      Mmb - member
//      Prm - parameter
//      b - Base
//      i1, i2 - Intermediate1, Intermediate2
//      f - final
class Base
{
    int bMmb;
public:
    Base(int);
    void ShowBase();
};
Base::Base (int bPrm)
{
    bMmb = bPrm;
}
void Base::ShowBase()
{
    cout << "Showing Base fields" << endl;
    cout << "bMmb = " << bMmb << endl; 
    cout << "----------------------------" << endl << endl;
}
class Intermediate1 : public Base
{
    int i1Mmb;
public:
    Intermediate1(int, int);
    void ShowIntermediate1();
};
Intermediate1::Intermediate1(int bPrm, int i1Prm):Base(bPrm)
{
    i1Mmb = i1Prm;
}
void Intermediate1::ShowIntermediate1()
{
    cout << "Showing Intermediate1 fields" << endl;
    cout << "i1Mmb = " << i1Mmb << endl;
    ShowBase();
}
class Intermediate2 : public Base
{
    int i2Mmb;
public:
    Intermediate2(int, int);
    void ShowIntermediate2();
};
Intermediate2::Intermediate2(int bPrm, int i2Prm):Base(bPrm)
{
    i2Mmb = i2Prm;
}
void Intermediate2::ShowIntermediate2()
{
    cout << "Showing Intermediate2 fields" << endl;
    cout << "i2Mmb = " << i2Mmb << endl;
    ShowBase();
}
class Final : public Intermediate1, public Intermediate2
{
    int fMmb;
public:
    Final(int, int, int, int);
    void ShowFinal();
};
Final::Final(int bPrm, int i1Prm, int i2Prm, int fPrm): Intermediate1(bPrm, i1Prm), Intermediate2(bPrm, i2Prm)
{
    fMmb = fPrm;
}
void Final::ShowFinal()
{
    cout << "Showing Final fields" << endl;
    cout << "fMmb = " << fMmb << endl;
    ShowIntermediate1();
    ShowIntermediate2();
}
void main()
{
    Base t(1);
    t.ShowBase();
    Intermediate1 u1(2, 31);
    u1.ShowIntermediate1();
    Intermediate2 u2(4, 51);
    u2.ShowIntermediate2();
    Final v(6, 71, 72, 8);
    v.ShowFinal();
}

谢谢你的帮助!

你的问题几乎没有限制,所以这应该可以工作。

将Intermediate1(和2)中的声明更改为

public:
    void ShowIntermediate1(bool printBase = true);

而在实现中:

...
if (printBase)
 ShowBase();

则在ShowFinal()中:

ShowIntermediate1(true);
ShowIntermediate2(false);

也许您正在寻找的答案是虚拟继承。这是用来解决钻石问题的。但是你应该修改你的代码来使用虚方法。