0
我寫了一個簡單的程序來處理重複繼承。 我用一個基類,兩個子類和孫子類多重繼承和繼承的數據成員在派生類構造函數初始化列表中
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;
};
這裏是老二類
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;
}
};
在主函數中我然後創建一個孫子對象並初始化它像這樣:
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對象中的數據值。我怎麼解決這個問題?
把這個告訴你的教授,因爲你沒有任何問題。 – P0W 2014-09-01 13:15:35
對不起,現在問題寫得更好了。謝謝 – Josh 2014-09-01 13:40:31
它不是使用的宏子對象的構造函數中的默認值,而是子對象的構造函數中的默認值。您實際上給A和B賦值,但不賦給CD和E,請檢查參數順序和默認值在你的子類中 – Drax 2014-09-01 13:48:44