/*
* 文件名称:继承和派生项目3.cpp
* 作 者: 杨晓东
* 完成日期: 2016 年 4 月 22 日
* 版 本 号:v1.0
* 对任务及求解方法的描述部分:继承和派生
* 输入描述:略
* 问题描述:略
* 程序输出:略
* 问题分析:略
* 算法设计:略
*/
一、问题及代码
#include <iostream>
#include <string.h>
#include <iomanip>//setw:设置输出数据的宽度,使用时应#include <iomanip.h>
using namespace std;
class CPerson
{
protected:
char *m_szName;
char *m_szId;
int m_nSex;//0:women,1:man
int m_nAge;
public:
CPerson(char *name,char *id,int sex,int age);
void Show1();
~CPerson(); //需要释放建立对象时动态分配的内存
};
class CEmployee:public CPerson
{
private:
char *m_szDepartment;
float m_Salary;
public:
CEmployee(char *name,char *id,int sex,int age,char *department,float salary);
void Show2();
~CEmployee();
};
CPerson::CPerson(char *name,char *id,int sex,int age)
{ m_szName=new char[20];
for(int i=0;i<20;++i)
m_szName[i]=*(name+i);
m_szId=new char[30];
for(int j=0;j<30;++j)
m_szId[j]=*(id+j);
m_nSex=sex;
m_nAge=age;
}
CEmployee::CEmployee(char *name,char *id,int sex,int age,char *department,float salary):CPerson(name,id,sex,age)
{
m_szDepartment=new char[20];
for(int i=0;i<20;++i)
m_szDepartment[i]=*(department+i);
m_Salary=salary;
}
void CPerson ::Show1()
{
cout<<setw(5)<<m_szName<<setw(20)<<m_szId<<setw(9)<<((m_nSex==0)?"women":"men")<<setw(6)<<m_nAge;
}
void CEmployee::Show2()
{
cout<<setw(6)<<"name"<<setw(19)<<"id"<<setw(9)<<"sex"<<setw(7)<<"age"<<setw(12)<<"department"<<setw(8)<<"salary"<<endl;
Show1();
cout<<setw(11)<<m_szDepartment<<setw(9)<<m_Salary<<endl;
}
CPerson::~CPerson()
{
delete []m_szName;
delete []m_szId;
}
CEmployee::~CEmployee()
{
delete []m_szDepartment;
}
int main()
{
char name[10],id[19],department[10];
int sex,age;
float salary;
cout<<<span style="color: rgb(0, 0, 255); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);">"请输入雇员的姓名,ID,性别(0:女,1:男),年龄,部门,薪水</span>:\n";
cin>>name>>id>>sex>>age>>department>>salary;
CEmployee employee1(name,id,sex,age,department,salary);
employee1.Show2();
system("pause");
return 0;
}
二、运行结果
<img src="https://img-blog.csdn.net/20160422110835875?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />
三、心得体会:继承和派生
四、知识点总结:继承和派生的应用