(1)定义名为CPerson的类,该类拥有属性:name、sex和age;
(2)为CPerson类设计相应的构造函数、析构函数和成员函数,能通过成员函数设置和获取数据成员;
(3)由类CPerson派生出子类CEmployee,为该类增加两个新的数据成员,分别用于表示部门(department)和薪水(salary);
(4)要求派生类CEmployee的构造函数显式调用基类CPerson的构造函数;
(5)为派生类CEmployee增加需要的成员函数;
(6)在主程序中定义CEmployee的对象,观察构造函数与析构函数的调用顺序;
#include<bits/stdc++.h>
using namespace std;
class CPerson{
protected:
char *name;
char *sex;
int age;
public:
CPerson(const char *name_,const char *sex_,int age_){strcpy(name,name_);strcpy(sex,sex_);age=age_;}
~CPerson();
void print(){
cout<<"姓名:"<<name<<endl;
cout<<"性别:"<<sex<<endl;
cout<<"年龄:"<<age<<endl;
}
};
class CEmployee: public CPerson{
private:
char *department;
float salary;
public:
CEmployee(const char *n,const char *s,int ag,const char *dep,float sal){//???
void print(){
CPerson::print();
cout<<"部门:"<<department<<endl;
cout<<"薪水:"<<salary<<endl;
}
}
};
int main(){
CEmployee C1("wanng","Girl",19,"SCT",8000);
C1.print();
return 0;
}
CEmployee(const char *n,const char *s,int ag,const char *dep,float sal) :CPerson(n,s,ag) {}
#include<bits/stdc++.h>
using namespace std;
class CPerson{
protected:
char name[30];
char sex[4];
int age;
public:
CPerson(const char *name_,const char *sex_,int age_){cout<<"Person 构造"<<endl;strcpy(name,name_);strcpy(sex,sex_);age=age_;}
~CPerson() {cout<<"Person 析构"<<endl;}
void print(){
cout<<"姓名:"<<name<<endl;
cout<<"性别:"<<sex<<endl;
cout<<"年龄:"<<age<<endl;
}
};
class CEmployee: public CPerson{
private:
char department[30];
float salary;
public:
CEmployee(const char *n,const char *s,int ag,const char *dep,float sal) : CPerson(n,s,ag)
{
cout<<"Employee 构造"<<endl;
salary = sal;
strcpy(department,dep);
}
void print()
{
CPerson::print();
cout<<"部门:"<<department<<endl;
cout<<"薪水:"<<salary<<endl;
}
~CEmployee() {cout<<"Employee 析构"<<endl;}
};
int main(){
CEmployee *pC = new CEmployee("wanng","Girl",19,"SCT",8000);
C1->print();
delete pC;
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!