c++抽象类编程小案例

原创
2017/03/04 18:26
阅读数 320

编写一个C++程序, 计算程序员( programmer )工资
1 要求能计算出
    初级程序员( junior_programmer )
    中级程序员 ( mid_programmer )
    高级程序员( adv_programmer)的工资
2 要求利用抽象类统一界面,方便程序的扩展,
    比如:新增, 计算 架构师 (architect ) 的工资
 

C++中没有Java中的接口概念,抽象类可以模拟Java中的接口类。(接口和协议)

下面程序定义一个程序员的类,里面有纯虚函数。

#include <iostream>
using namespace std;

class programmer
{
public:
	virtual void getSal() = 0;
};

//初级程序员
class junior_programmer :public programmer
{
public:
	junior_programmer(char *name,char *job,int sal)
	{
		this->name = name;
		this->job  = job;
		this->sal  = sal;
	}
	virtual void getSal()
	{
		cout << name << " " << job << " : " << sal << endl;
	}
private:
	char *name;
	char *job;
	int sal;
};

//中级程序员
class mid_programmer :public programmer
{
public:
	mid_programmer(char *name, char *job, int sal)
	{
		this->name = name;
		this->job = job;
		this->sal = sal;
	}
	virtual void getSal()
	{
		cout << name << " " << job << " : " << sal << endl;
	}
private:
	char *name;
	char *job;
	int sal;
};

//高级程序员
class adv_programmer :public programmer
{
public:
	adv_programmer(char *name, char *job, int sal)
	{
		this->name = name;
		this->job = job;
		this->sal = sal;
	}
	virtual void getSal()
	{
		cout << name << " " << job << " : " << sal << endl;
	}
private:
	char *name;
	char *job;
	int sal;
};

//架构师
class architect :public programmer
{
public:
	architect(char *name, char *job, int sal)
	{
		this->name = name;
		this->job = job;
		this->sal = sal;
	}
	virtual void getSal()
	{
		cout << name << " " << job << " : " << sal << endl;
	}
private:
	char *name;
	char *job;
	int sal;
};

//计算工资,简单的框架
void call_programer_sal(programmer *base)
{
	base->getSal();
}

int main()
{
	junior_programmer jp("小赵", "初级程序员", 4000);
	mid_programmer    mp("小钱", "中级程序员", 8000);
	adv_programmer	  ap("小王", "高级程序员", 12000);

	//系统扩展
	architect   arch_pro("小周", "架构师", 16000);

	call_programer_sal(&jp);
	call_programer_sal(&mp);
	call_programer_sal(&ap);
	call_programer_sal(&arch_pro);

	return 0;
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部