定义一个person类,私有数据成员有年龄(age,int),姓名(name,string),性别(sex, char);公有函数有:doJob(string job),返回“是个。。。”工作由doJob()的参数job决定;访问数据成员的setter和getter方法;一个 family类,私有成员有father (father ,person),mother(mother,person),doughter(dughter,person),son(son,person),公有函数有:访问数据成员的setter和getter方法。在main()中分别实例化一个person类和family类的对象,调用各数据成员的成员方法,设置和输出各个成员的数据成员。运行结果如下所示:如:父亲:John,59岁,是个医生母亲:Marry,50岁,是个教师女儿。。。。。儿子。。。。Ps:以下是我写的mian函数不知道怎么写。不知道怎么把那两个类连起来。#include<iostream>#include<string>using namespace std;class person{private:int age;string name;char sex;public:void setName(string sname);string getName();void setAge(int sage);int getAge();void setSex(char ssex);char getSex();void doJob(string job);};class family{private:person father;person mother;person doughter;person son;public:void setFather(person sfather){father=sfather;}person getFather(){return father;}void setMother(person smother){mother=smother;}person getMother(){return mother;}void setDoughter(person sdoughter){doughter=sdoughter;}person getDoughter(){return doughter;}void setSon(person sson){son=sson;}person getSon(){return son;}};void person::setName(string sname){name=sname;}string person::getName(){return name;}void person::setAge(int sage){age=sage;}int person::getAge(){return age;}void person::setSex(char ssex){sex=ssex;}char person::getSex(){return sex;}void person::doJob(string job){cout<<"是个"<<job;}int main(){family family1;person f;family1.setFather(f);cout<<"父亲:";family1.getFather().setName("John");family1.getFather().setAge(50);family1.getFather().setSex('M');cout<<family1.getFather().getName()<<","<<family1.getFather().getAge()<<"岁,";family1.getFather().doJob("医生.");cout<<endl;return 0;}
2 回答
莫回无
TA贡献1865条经验 获得超7个赞
你没有在person类中定义操作符=
在你的person类中添加这个重载:
person& operator = (const person &B)
{
age=B.age;
name=B.name;
sex=B.sex;
return *this;
}
然后修改你的main函数
int main()
{
family family1;
person f;
f.setAge(20);
f.setName("John");
f.setSex('M');
family1.setFather(f);
cout<<"父亲:";
cout<<family1.getFather().getName()<<","
<<family1.getFather().getAge()<<"岁,";
family1.getFather().doJob("医生.");
cout<<endl;
return 0;
}
是先设置person ,然后再把person类赋给family,是先有人,才有家滴哦
添加回答
举报
0/150
提交
取消