多重继承和继承的数据成员在派生类构造函数初始化列表中

问题描述:

我写了一个简单的程序来处理重复继承。 我用一个基类,两个子类和孙子类多重继承和继承的数据成员在派生类构造函数初始化列表中

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对象中的数据值。我怎么解决这个问题?

+1

把这个告诉你的教授,因为你没有任何问题。 – P0W 2014-09-01 13:15:35

+0

对不起,现在问题写得更好了。谢谢 – Josh 2014-09-01 13:40:31

+1

它不是使用的宏子对象的构造函数中的默认值,而是子对象的构造函数中的默认值。您实际上给A和B赋值,但不赋给CD和E,请检查参数顺序和默认值在你的子类中 – Drax 2014-09-01 13:48:44

为了让代码工作,我想我做了这些改变

//Constructor with explicitly inherited data members 
GrandChild(string Word, double A, double B, string Text, double C, double D, 
     string Name, double E, double F): 
      Child1(Word, A, B, Text, C, D), 
       Child2(Word, A, B, Name, E, F){ } 

基本上每个子类继承了自己独立的父类。此父类的数据成员出现在两个子类构造函数列表中。在构造GrandChild类时,我将这些值声明为其构造函数中的参数(仅用于避免重复)!我还包括继承的子类。

在主然后我可以像这样创建一个孙子对象:

GrandChild gObj("n\a", 0.00, 0.00, "text", 3, 3, "text", 3, 3, 7); 

并使用点运算符和无效的成员函数我得到正确的答案:

gObj.Operation() 

是:

sum: 12