C++ 员工工资(虚函数与多态)

题目描述
某公司员工的属性有:姓名、职位、级别、工作年限,级别和年限都是非负整数,否则显示错误。包含方法有:构造函数,计算工资的方法(salary())。

员工职位分为三种:Employee、Teamleader、Manager,其他职位类型显示错误。

三种职位员工的区别在于计算工资的方法不同:

  1. Employee的每月工资 = 1000 + 500级别 + 50工作年限

  2. Teamleader的每月工资 = 3000 + 800级别 + 100工作年限

  3. Manager的每月工资 = 5000 + 1000 * (级别+工作年限)

计算工资的方法返回每个员工的工资数。

要求:以普通员工为基类,组长和经理继承基类,程序中只能使用基类指针指向对象与调用对象的方法。

输入
测试案例的个数 t

每行输入一个员工的信息:包括姓名、职位、级别、工作年限

输出
输出相应员工的信息

如有错误信息,则输出错误信息,若职位信息与级别和年限信息同时出错,仅输出职位错误信息

样例输入
5
zhangsan Employee 4 5
lisi Teamleader 4 5
Wangwu Manager 4 5
chenliu Precident 4 5
xiaoxiao Manager -1 5
样例输出
zhangsan:Employee,Salary:3250
lisi:Teamleader,Salary:6700
Wangwu:Manager,Salary:14000
error position.
error grade or year.

#include<iostream>
#include <cstring>
using namespace std;
class Employee{
	protected:
		char *name;
		char *position;
		int level,year;
	public:
		Employee(char *n,char *p,int l,int y){
			name=new char[strlen(n)+1];
			strcpy(name,n);
			position=new char[strlen(p)+1];
			strcpy(position,p);
			level=l;
			year=y;
		}
		virtual int salary(){
			return 1000+500*level+50*year;
		}
		void print(){
			cout<<name<<":"<<position<<",Salary:"<<salary()<<endl;
		}
		virtual ~Employee(){
				if(name!=NULL)
					delete name;
				if(position!=NULL)
					delete position;
		}
};
class Teamleader:public Employee{
	public:
		Teamleader(char *n,char *p,int l,int y):Employee(n,p,l,y){	}
		virtual int salary(){
			return 3000+800*level+100*year;
		}
};
class Manager:public Employee{
	public:
		Manager(char *n,char *p,int l,int y):Employee(n,p,l,y){	}
		virtual int salary(){
			return 5000+1000*(level+year);
		}
};
int main(){
	int t,l,y,i,j;
	char n[20],p[20];
	Employee *E;
	cin>>t;
	while(t--){
		i=0;j=0;	//i和j来判断输入的数据是否符合要求
		cin>>n>>p>>l>>y;
		if(l<0||y<0)
			j=1;	//日期错误情况
		if(!strcmp(p,"Employee"))
			i=1;		
		if(!strcmp(p,"Teamleader"))
			i=2;	
		if(!strcmp(p,"Manager"))
			i=3;
		if(j==0&&i!=0)
		switch(i){	//根据i的值确定创建的是什么类的对象
			case 1:{
				Employee e1(n,p,l,y);
				E=&e1;
				E->print();
				break;
			}
			case 2:{
				Teamleader t1(n,p,l,y);
				E=&t1;
				E->print();
				break;
			} 
			case 3:{
				Manager m1(n,p,l,y);
				E=&m1;
				E->print();
				break;
			}
		}
		if(j==1&&i!=0)	//当只有日期错误的输出
			cout<<"error grade or year."<<endl;
		if((i==0)||(i==0&&j==1)){		//题目要求当日期和职位都出错时,输出职位错误				
			cout<<"error position."<<endl;
		}
		
	}
}

在这里插入图片描述

  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值