问题及代码:
/*
*烟台大学计算机学院
*文件名称:xiangmu3(2).cpp
*作 者:闫安
*完成日期:2016年5月22日
*版 本 号:codeblocks 16.01
*
*问题描述:为Polic类和Cook类增加了对象成员,请扩充代码,完成上述各项要求
*程序输入:无
*程序输出:各个对象的属性
*/
#include<iostream>
#include<string>
using namespace std;
class Person //人类
{
public:
Person(int a,string nam):age(a),name(nam){}; //构造函数
void action();
string getName()
{
return name;
}
private:
int age;
string name;
};
void Person::action()
{
cout<<name<<" do some action"<<endl;
}
class Police:public Person //警察类,一人类为基类
{
public:
Police(int a,string nam,int le,Person p):Person(a,nam),level(le),leader(p){}; //构造函数
void arrest(Person p);
void show();
private:
int level; //级别
Person leader; //领导
};
void Police::arrest(Person p)
{
cout<<"Police "<<getName()<<" arrest " <<p.getName()<<endl;
}
void Police::show()
{
cout<<"Police "<<getName()<<", leader is " <<leader.getName()<<endl;
}
class Cook:public Person //厨师类,以人类为基类
{
public:
Cook(int a,string nam,double s,Police p):Person(a,nam),salary(s),protector(p){}; // 构造函数
void getCake(int n);
void show();
private:
double salary; //薪水
Police protector; //保安
};
void Cook::getCake(int n)
{
cout<<"Cook "<<getName()<<" gave me " <<n<<" cakes."<<endl;
}
void Cook::show()
{
cout<<"Cook "<<getName()<<" is protected by Police "<<protector.getName()<<endl;
}
int main()
{
Person jerry(43,"Jerry");
Police jack(30,"Jack",2,jerry);
Cook john(24,"John",5000,jack);
jack.show();
john.show();
return 0;
}
运行结果:
知识点总结:
运用派生类
学习心得:
要注意构造函数的编写,开始错了好几次