c++ 多态练习 公司结构

这里我们的多态体现在Control类的Work函数和Show函数中
首先 定义我们的基类Person
#pragma once
#include
using namespace std;
#include
class Person
{
public:int nId;string strName;string strGw;
public:Person();void Show();virtual void Work() = 0;};
Person是一个抽象类
接下来 对Person进行具体编写
#include "Person.h"
Person::Person()
{nId = 0;strName = "";strGw = "";
}void Person::Show()
{cout << "id为 " << nId << "姓名为 " << strName<< "工种为 " << strGw << endl;}
其次 开始定义Boss类
#pragma once
#include "Person.h"
class Boss:public Person
{public:Boss(int nId,string Name,string Gw);void Work();};
#include "Boss.h"
Boss::Boss(int nId, string Name, string Gw)
{this->nId =nId;this->strName=Name;this->strGw=Gw;
}
void Boss::Work()
{cout << "管理所有人" << endl;
}
在定义一个员工类Staff
#pragma once
#include"Person.h"
class Staff:public Person
{
public:void Work();Staff(int nId, string Name, string Gw);
};
#include "Staff.h"Staff::Staff(int nId, string Name, string Gw)
{this->nId = nId;this->strName = Name;this->strGw = Gw;
}void Staff::Work()
{cout << "打工" << endl;
};
然后开始对Control进行编写
#pragma once
#include"Person.h"
#include"Boss.h"
#include"Staff.h"
class Control
{
public:Person* arr[10];
public:Control();void AddStaff(Person* pPs);void Show();void Work();
};
#include "Control.h"
Control::Control()
{for (int i = 0; i < 10; i++){arr[i] = NULL;}//==}void Control::AddStaff(Person* pPs)
{for (int i = 0; i < 10; i++){if (arr[i] == NULL){arr[i]=pPs;return;}}cout << "编制已满" << endl;}
void Control::Show(){for (int i = 0; i < 10; i++){if (arr[i] != NULL){arr[i]->Show();}else{cout << "------- " << endl;}}}
void Control::Work()
{for (int i = 0; i < 10; i++){if (arr[i] != NULL){arr[i]->Work();}else{cout << "------- " << endl;}}}
主函数中
#include"Control.h"
int main()
{Control Co;Person *ps1=new Boss(1,"王大拿","董事长");Person *ps2=new Staff(2,"宋晓峰","打工人");Co.AddStaff(ps1);Co.AddStaff(ps2);Co.Show();Co.Work();return 0;
}
输出为

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
