问题描述及代码:
/*
*copyright (c) 2016,烟台大学计算机学院
*All rights reserved.
*文件名称:hellow.cpp
*作者:田甜
*完成日期:2016年5月14日
*版本号:v1.0
*
*问题描述:(1)根据类图,定义各个类,各个成员函数,只要输出相关的信息即可,暂不深究其业务功能 。请为各个类增加构造函数 。
在实现中,可以增加需要的其他函数。
自行编制main函数,完成初步的测试。
*输入描述:
*程序输出:///
*/
#include <iostream>
using namespace std;
class Person
{
private:
string name;
int age;
public:
Person(string nam,int a):name(nam),age(a){}
void action();
string get_name()
{
return name;
}
};
void Person::action()
{
cout<<name<<" do some action."<<endl;
}
class Police:public Person
{
private:
int level;
public:
Police(string nam,int a,int l):Person(nam,a),level(l){}
void arrest(Person &p);
};
void Police::arrest(Person &p)
{
cout<<"Police "<<get_name()<<" arrest "<<p.get_name()<<"."<<endl;
}
class Cook:public Person
{
private:
double salary;
public:
Cook(string nam,int a,double s):Person(nam,a),salary(s){}
void get_cooked(int n);
};
void Cook::get_cooked(int n)
{
cout<<"Cooker "<<get_name()<<" has cooked "<<n<<" foods."<<endl;
}
int main()
{
Police p("li",22,3);
Cook c("wang",21,3000);
p.action();
c.action();
p.arrest(c);
c.get_cooked(3);
return 0;
}
运行结果:
心得体会:
警察类中的成员函数里的arrest有Person类的形参,而Cook类作为Person类的子类其对象可以作为Person类充当形参。