_Phoebe__ 2022-03-21 13:12 采纳率: 96.9%
浏览 20
已结题

一个继承与派生的问题 编译不通过 显式调用(要求4 5 6 7)也不会实现 想知道怎么改

(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;
}
  • 写回答

2条回答 默认 最新

  • CSDN专家-link 2022-03-21 13:20
    关注

    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;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月29日
  • 已采纳回答 3月21日
  • 创建了问题 3月21日