gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:42:56 29 4
gpt4 key购买 nike

我编写了一个处理重复继承的简单程序。我使用一个基类,两个子类和一个孙类

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 对象构造中的数据值。我该如何解决这个问题?

最佳答案

为了让代码按我希望的方式工作,我做了这些更改

  //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 类时,我在其构造函数中将这些值声明为参数(只声明一次以避免重复)!我还包括继承的子类。

然后在 main 中我可以像这样创建一个 GrandChild 对象:

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

然后使用点运算符和 void 成员函数我得到了正确的答案:

gObj.Operation()

即:

sum: 12

关于c++ - 派生类构造函数初始化列表中的多重继承和继承数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25606707/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com