c++ 多态练习 公司结构

这里我们的多态体现在Control类的Work函数和Show函数中 

首先 定义我们的基类Person

#pragma once
#include<iostream>
using namespace std;
#include<string>
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;
}

输出为

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值