/*
2.*Copyright(c) 2016.烟台大学计算机与控制工程学院
3.*ALL rights reserved.
4.*文件名称:main.cpp
5.*作者:孙亚茹
6.*完成日期:2016年5月19日
7.*问题描述:根据类图定义各个类。
8.*/
#include<iostream>
#include<string>
using namespace std;
class Person
{
private:
int age;
string name;
public:
Person(int ,string);
void action();
int getage(){return age;}
string getname(){return name;}
};
Person::Person(int a,string nam):age(a),name(nam){}
class Polic:public Person
{
private:
int level;
Person leader; // 增加了person 类的leader
public:
Polic(int ,string ,int ,Person );
void arrest(Person);
};
Polic::Polic(int a,string nam,int l , Person lea):Person(a,nam),level(l),leader(lea){}
class Cook:public Person
{
private:
double salary;
Polic protecter; // 增加了polic类的保护者
public:
Cook(int ,string ,double,Polic);
string getCake(int);
};
Cook::Cook(int a,string nam,double s , Polic aa):Person(a,nam),salary(s),protecter(aa){}
void Person::action()
{
cout<<name<<" have some action ."<<endl;
}
void Polic::arrest(Person p)
{
cout<<getname()<<" arrest "<<p.getname()<<" , "<<getname()<<" 的等级是 "<<level<<" , "<<getname()<<" 的年龄是 "<<getage()<<endl;
cout<<endl;
// police 的 leader
cout<<getname()<<" 的领导是 "<<leader.getname()<<endl;
cout<<endl;
cout<<leader.getname()<<" 的年龄是 "<<leader.getage()<<endl;
cout<<endl;
}
string Cook::getCake(int a)
{
cout<<getname()<<" get "<<a<<" cakes."<<endl;
cout<<endl;
// cook 的保护者
cout<<getname()<<" 的保护者是 "<<protecter.getname()<<endl;
return getname();
}
int main()
{
Person m(20,"person1.zhangsan");
Person leader1(20,"leader1.lisi");
Polic police(23,"police2.wangwu",3,leader1);
Cook cook(19,"cook3.sunliu",5000,police);
police.arrest(m);
cook.getCake(5);
return 0;
}
总结:
当一个派生类有多个基类时要保证每一个基类的访问权限都能被派生类访问。