栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 多态练习 公司结构

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;
}

输出为

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1009137.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号