#include<iostream>
#include<string.h>
using namespace std;
class Mother
{
protected:
string mname;
public:
Mother (string mname1)
{mname=mname1;}
string getMName()
{return mname;}
};
class Father
{
protected:
string fname;
public:
Father (string fname1)
{fname=fname1;}
string getFName()
{return fname;}
};
class Child : public Mother, public Father // MultipleInheritance
{
private:
string cname;[enter image description here][1]
public:
Child ()
{
cout<<"What is your MOTHER name? : " << endl ;
cin >> mname;
cout << "What is your FATHER name? : " << endl;
cin >> fname;
cout <<"What is your YOUR name? : "<< endl ;
cin >> cname;
}
Child (string mname1 , string fname1, string cname1)
{mname=mname1; fname=fname1;cname=cname1;}
string getCName()
{return cname;}
};
int main ()
{
Child c1;
Child c2 ("Amneh","Ahmad","Mohammad");
cout<<"First constructor >>> Mother Name : \t"<< c1.getMName()<<"Father Name : "<< c1.getFName()<<"Child Name : " <<c1.getCName()<<endl;
cout<<"Second constructor >>> Mother Name : \t"<< c2.getMName()<<"Father Name : "<< c2.getFName()<<"Child Name : " <<c2.getCName()<<endl;
}
创建上面显示的类,注意Child类继承自Mother类和Father类。创建一个Child对象。使用show()函数打印出母亲的父亲和孩子的名字。
这是代码中的错误?我尝试了许多方式,但没有工作。一世 需要创建继承自2个类的类..这是我的第一个 stackoverflow中的时间帖子。 :) 谢谢。 Mohammad El-Musleh
答案 0 :(得分:2)
Mother
和Father
每个只有一个构造函数,并且该构造函数接受一个字符串,因此您必须在Child
的构造函数中提供该字符串。
public:
Child (string name, string mname, string fname)
:Mother(mnane), Father(fname)
{
cname = name;
}
此外,要求名称的代码必须在构造函数之外(并且最好完全在类之外)
答案 1 :(得分:0)
谢谢 James Curran 如果有人想查看最终代码,我希望它可以帮到你。
这是代码的新更新。
#include<iostream>
#include<string.h>
using namespace std;
class Mother
{
protected:
string mname;
public:
Mother (string mname1)
{mname=mname1;}
string getMName()
{return mname;}
};
class Father
{
protected:
string fname;
public:
Father (string fname1)
{fname=fname1;}
string getFName()
{return fname;}
};
class Child : public Mother, public Father // MultipleInheritance
{
private:
string cname;
public:
Child (string mname1 , string fname1, string cname1);
string getCName();
};
Child :: Child (string mname1, string fname1, string cname1) : Mother(mname1), Father(fname1)
{cname=cname1;}
string Child :: getCName()
{return cname;}
void show() //I use constructor
{
Child c2 ("Amneh","Ahmad","Mohammad");
cout<<"Constructor >>>\n Mother Name : "<< c2.getMName()<<"\n Father Name : "<< c2.getFName()<<"\n Child Name : " <<c2.getCName()<<endl;
}
int main ()
{
show();
}