#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
//创建一个抽象类
class Worker
{
public:
Worker()
{
inum++; //静态变量的变化值
mID = inum; //每增加一个员工,它的 ID 会自动加一
mName = "NoDefined";
mSalary = 0.0;
}
virtual ~Worker(){ } //基类的析构函数一般写成虚继承,可以做到把基类和子类对象一起析构
virtual void GetPay() = 0; //不同的计算工资方法(纯虚函数)
virtual void Show() //在基类中实现出来,如果内容相同,子类就不用再实现了
{
cout << "姓名:" << mName << " ID:" << mID << " 工资:" << mSalary << endl;
}
protected:
int mID; // 员工编号
string mName; // 姓名
double mSalary; // 月薪
static int inum; // 统计器
};
int Worker::inum = 1000;
//技术人员
class Technician : public Worker
{
public:
Technician(string name, int hour = 0)
{
mName = name;
mHour = hour;
}
virtual void GetPay()
{
mSalary = mHour * 100;
}
protected:
int mHour; // 工时
};
//经理
class Manager : virtual public Worker
{
protected:
Manager(){}
public:
Manager(string name)
{
mName = name;
base = 8000;
}
virtual void GetPay()
{
mSalary = base;
}
protected:
double base; // 基本工资
};
//销售人员
class SalesMan : virtual public Worker
{
protected:
SalesMan(){}
public:
SalesMan(string name, double count = 0)
{
mName = name;
mCount = count;
}
virtual void GetPay()
{
mSalary = mCount * 4 / 100;
}
protected:
double mCount;
};
//销售经理
class SalesManager : public SalesMan, public Manager //此处用了虚继承,解决了二义性
{
public:
SalesManager(string name, double count)
{
base = 5000;
mName = name;
mCount = count;
}
virtual void GetPay()
{
mSalary = base + mCount * 5 / 100;
}
};
//打印输出
void printInfo(Worker& emp)
{
// 这里使用的就是多态性来调用的函数
emp.GetPay();
emp.Show();
}
int main()
{
Manager m1("xiao yong");
Technician t1("xiao ming", 200);
SalesMan s1("xiao hong", 80000);
SalesManager sm1("xiao yong", 100000);
printInfo(m1);
printInfo(t1);
printInfo(s1);
printInfo(sm1);
// 暂停
system("pause");
return EXIT_SUCCESS;
}