繰り返し継承を処理する簡単なプログラムを作成しました。基本クラス、2 つの子クラス、および孫クラスを使用します
class Parent{
public:
Parent(string Word = "", double A = 1.00, double B = 1.00): sWord(Word), dA(A), dB(B){
}
//Member function
void Operation(){
cout << dA << " + " << dB << " = " << (dA + dB) << endl;
}
protected:
string sWord;
double dA;
double dB;
};
これが最初の子クラスです
class Child1 : public Parent{
public:
//Constructor with initialisation list and inherited data values from Parent class
Child1(string Word, double A, double B , string Text = "" , double C = 0.00, double D = 0.00): Parent(Word, A, B), sText(Text), dC(C), dD(D){};
//member function
void Operation(){
cout << dA << " x " << dB << " x " << dC << " x " << dD << " = " << (dA*dB*dC*dD) << endl;}
void Average(){
cout << "Average: " << ((dA+dB+dC+dD)/4) << endl;}
protected:
string sText;
double dC;
double dD;
};
これが2番目の子クラスです
class Child2 : public Parent {
public:
//Constructor with explicit inherited initialisation list and inherited data values from Base Class
Child2(string Word, double A, double B, string Name = "", double E = 0.00, double F = 0.00): Parent(Word, A, B), sName(Name), dE(E), dF(F){}
//member functions
void Operation(){
cout << "( " << dA << " x " << dB << " ) - ( " << dE << " / " << dF << " )" << " = "
<< (dA*dB)-(dE/dF) << endl;}
void Average(){
cout << "Average: " << ((dA+dB+dE+dF)/4) << endl;}
protected:
string sName;
double dE;
double dF;
};
多重継承を扱う孫クラスはこちら
class GrandChild : public Child1, public Child2{
public:
//Constructor with explicitly inherited data members
GrandChild(string Text, double C, double D,
string Name, double E, double F): Child1(Text, C, D), Child2(Name, E, F){}
//member function
void Operation(){
cout << "Sum: " << (dC + dD + dE + dF) << endl;
}
};
main 関数で、GrandChild オブジェクトを作成し、次のように初期化します。
GrandChild gObj("N\A", 24, 7, "N\A", 19, 6);
//calling the void data member function in the GrandChild class
gObj.Operation();
これに対する私が得た答えは
SUM: 0
ただし、答えは 56 のはずです。明らかに、GrandChild オブジェクトの構築に含まれるデータ値ではなく、GrandChild クラスのコンストラクターで使用されるデフォルトの継承値が使用されています。どうすればこの問題を解決できますか?