问题及代码:
/*copyright 计算机与控制工程学院
完成日期:2016年5月8日
作者:马艳艳
问题描述:各个成员函数,只要输出相关的信息即可,暂不深究其业务功能
请为各个类增加构造函数
在实现中,可以增加需要的其他函数
自行编制main函数,完成初步的测试
输入描述:无
输出描述:成员信息
*/
#include <iostream>
using namespace std;
class Person
{
public:
Person(int ,string ,string);
void action();
string getN(){return name;}
int getA(){return age;}
string getS(){return sex;}
private:
int age;
string name;
string sex;
};
Person::Person (int a,string n,string s):age(a),name(n),sex(s){}//给人,定义构造函数,包括年名名字性别
void Person::action()
{
cout<<name<<"is doing something "<<endl;
}
class Police:public Person
{
public:
Police (int ,string,string ,int,Person);
void arrest(Person);
void show();
private:
int level;// 级别
Person leader;
};
Police::Police(int a,string n,string s,int l,Person p):Person(a,n,s),level(l),leader(p){}
void Police::arrest(Person p)
{
cout<<"Police "<<" "<<getN()<<" "<<"whose sex is "<<p.getS()<<" "<<"arrrest"<<" "<<p.getN()<<endl;
}
void Police:: show()
{
cout<<"Police "<<getN()<<", leader is "<<leader.getN()<<endl;
}
class Cook:public Person
{
public:
Cook(int ,string,string,double,Police );
void getC(int );
void show();
private:
double salary;
Police protector;
};
Cook::Cook(int a,string n,string s, double sa,Police p):Person(a,n,s),salary(sa),protector(p){}
void Cook::getC(int n)
{
cout<<" A Cook a "<<" "<<getS()<<" "<<getN()<<" "<<"give"<<" "<<n<<" "<<"cakes"<<endl;
}
void Cook::show()
{
cout<<"Cook "<<getN()<<" is protected by police "<<protector.getN()<<endl;
}
int main()
{
Person Tom(40,"Tom","male");
Police Jack(30,"Jack","male",2,Tom);
Cook Mary(24,"Mary","female",5000,Jack);
Jack.show();
Mary.show();
return 0;
}
运行结果:
知识点总结:
我们希望看到jack警察的上司就是一个人,john厨师的保卫者,就是一个警察。
- 需要做的是,利用对象作为构造函数的参数,使结构清晰。
- 当然,这时需要增加相关的复制构造函数了。可以使用默认复制构造函数。