C++ day5 类的继承

定义一个学生类(Student):私有成员属性(姓名、年龄、分数)、成员方法(无参构造、有参构造、析构函数、show函数)​

再定义一个党员类(Party):私有成员属性(党组织活动,组织),成员方法

由这两个类共同派生出学生干部类,私有成员属性(职位),成员方法(无参构造、有参构造、析构函数、show函数),使用学生干部类实例化一个对象,然后调用其show函数进行测试

#include <iostream>

using namespace std;

class Stu //定义学生类
{
private:
    string name; //姓名
    int age;     //年龄
    double score;//分数
public:
    Stu()//无参构造
    {
        cout << "Stu::无参构造" << endl;
    }
    Stu(string name, int age, double score):name(name), age(age), score(score)//有参构造
    {
        cout << "Stu::有参构造" << endl;
    }
    ~Stu()//析构函数
    {
        cout << "Stu::析构函数" << endl;
    }
    void show()//show函数
    {
        cout << "name = " << name << endl;
        cout << "age = " << age << endl;
        cout << "score = " << score << endl;
    }
};

class Party //定义党员类
{
private:
    string act; //党组织活动
    string org; //组织
public:
    Party()//无参构造
    {
        cout << "Party::无参构造" << endl;
    }
    Party(string act, string org):act(act), org(org)//有参构造
    {
        cout << "Party::有参构造" << endl;
    }
    ~Party()//析构函数
    {
        cout << "Party::析构函数" << endl;
    }
    void show()//show函数
    {
        cout << "act = " << act << endl;
        cout << "org = " << org << endl;
    }


};

//由这两个类共同派生出学生干部类
class Leader: public Stu, public Party
{
private:
    string post;
public:
   Leader()//无参构造
    {
        cout << "Leader::无参构造" << endl;
    }
    Leader(string name, int age, double score, string act, string org, string post):\
        Stu(name, age, score), Party(act, org), post(post)//有参构造
    {
        cout << "Leader::有参构造" << endl;
    }
    ~Leader()//析构函数
    {
        cout << "Leader::析构函数" << endl;
    }

    void show()//show函数
    {
        Stu::show();
        Party::show();
        cout << "post = " << post << endl;
        //私有成员,继承后子类无法访问
        //cout << "name = " << name << endl;
        //cout << "age = " << age << endl;
        //cout << "score = " << score << endl;
        //cout << "act = " << act << endl;
        //cout << "org = " << org << endl;
    }
};

int main()
{
    Leader l("zhangsan", 19, 99.5, "aa", "bb", "cc");
    l.show();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值