<pre name="code" class="cpp">/*copyright(c)2016.烟台大学计算机学院
* All rights reserved,
* 文件名称:text.Cpp
* 作者:刘涛
* 完成日期:2016年5月7日
* 版本号:vc++6.0
* 问题描述:(1)根据下面的类图,定义各个类:
这里写图片描述。(图片见附件)
要求:各个成员函数,只要输出相关的信息即可,
暂不深究其业务功能请为各个类增加构造函
数在实现中,可以增加需要的其他函数自行
编制main函数,完成初步的测试。
*/
#include<iostream>
using namespace std;
class Person
{
private:
int age;
string name;
public:
Person(int a,string nam):age(a),name(nam){}
void action();
void show();
string getName()
{
return name;
}
};
void Person::action()
{
cout<<name<<"放了个屁"<<endl;
}
void Person::show()
{
cout<<"自己表示很难闻"<<endl;
}
/*****************************************/
class Police: public Person
{
public:
Police(int a, string n,int l,Person lea):Person(a,n),level(l),leader(lea){}
void arrest(Person);
void show();
private:
int level;
Person leader;
};
void Police::arrest(Person p)
{
cout<<"police:"<<getName()<<"因为放屁抓捕了"<<p.getName()<<endl;
}
void Police::show()
{
cout<<"ploice:"<<getName()<<" "<<level<<" level"<<",his leader is "<<leader.getName()<<endl;
}
/*****************************************/
class Cook:public Person
{
public:
Cook(int a,string n,double s,Police p):Person(a,n),salary(s),protector(p){}
void getCake(int);
void show();
private:
double salary;
Police protector;
};
void Cook::getCake(int p1)
{
cout<<"Cook:"<<getName()<<"做了"<<p1<<"个蛋糕"<<endl;
}
void Cook::show()
{
cout<<"Cook:"<<getName()<<" is protected by Police "<<protector.getName()<<endl;
}
/****************************************/
int main()
{
Person L(27,"love");
Police J(31,"james",10,L);
Cook I(24,"irving",500,J);
L.action();
L.show();
J.arrest(L);
J.show();
I.getCake(5);
I.show();
return 0;
}
运行结果:
学习心得:老师这个程序给了两个做法,我觉得两个都不好,第一个的话太过繁琐,每个构造函数带上一长串的参数,
-这种写法,也根本未体现对象的“封装”——都是一串散乱的基本类型数据在工作。 然后第二个不好之处在于不能换人,只能在person,police,cook之间产生关系,police可不能抓自己的上司啊。
关键之处在于利用对象作为构造函数的参数,police中的leader是基类中的person,cook中的警察是派生类中的police。这样就解决了太过繁琐的问题。