我在多重继承菱形方案下组织了4个班级。
BASE
/ \
/ \
Deriv1 Deriv2
\ /
\ /
Final
我有每个类“ShowXXXX()”方法(例如),其中'XXXX'是该类的名称。
当我调用“ob.ShowFinal()
”方法时,它会打印:
问题是我想第二次逃避打印Base的字段。
但是,有一种范例:因为当我打电话给“ob.ShowDeriv2()
”时应该打印出来:
当我打电话给“ob.ShowDeriv1()
”时,应打印出来:
我的代码:
// 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();
}
谢谢你的帮助!
答案 0 :(得分:1)
你的问题几乎没有限制,所以这应该有用。
将Intermediate1(和2)中的声明更改为
public:
void ShowIntermediate1(bool printBase = true);
在实施中:
...
if (printBase)
ShowBase();
然后在ShowFinal()
:
ShowIntermediate1(true);
ShowIntermediate2(false);
答案 1 :(得分:0)
也许您正在寻找的答案是virtual inheritance。这旨在解决diamond problem。但是,您应该更改代码以使用虚拟方法。