【发布时间】:2014-09-01 13:13:32
【问题描述】:
我编写了一个处理重复继承的简单程序。 我使用一个基类、两个子类和一个孙类
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 对象并像这样初始化它:
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 对象的构造中包含的数据值。我该如何解决这个问题?
【问题讨论】:
-
把这个告诉你的教授,因为你没有任何问题。
-
对不起,这个问题现在写得更好了。谢谢
-
使用的不是大子对象的构造函数中的默认值,而是子对象的构造函数中的默认值..您实际上给A和B赋值,但没有给CD 和 E,检查您的子类中的参数顺序和默认值
-
当我在相应的子构造函数中更改 C D E 和 F 的值时,void Operation() 会相应地显示不同的结果。
-
但是我想要的是提供给对象 gObj 的数据值用于代替这些默认值。我该怎么做?
标签: c++ multiple-inheritance qualifiers