派生类

1.派生类是对类的具体化,而类是派生类的抽象。
2.派生类的声明方式:**class 派生类名 继承方式  基类名。**
3.派生类的继承方式有protected private public。
4.公用继承的介绍:
代码示例如下:

#include<iostream>
#include<string>
using namespace std;
class Student//声明基类
{
public:
    void get_1()//输入姓名及性别
    {
        cin >> name >> sex;
    }
    void display_1()//输出姓名性别
    {
        cout << "姓名:" << name << " " << "性别:" << sex << endl;
    }
private:
    string sex;
    string name;
};
class Student1 :public Student//声明派生类,继承方式为public
{
public:
    void get_2()//输入成绩学号
    {
        cin >> score >> num;
    }
    void display_2()//输出成绩学号
    {
        cout << "成绩:" << score << " " << "学号:" << num << endl;
    }
private:
    int score;
    int num;
};
int main()
{
    Student1 s;//定义派生类对象
    s.get_1();
    s.get_2();
    s.display_1();
    s.display_2();
    return 0;
}


代码还可以更优化如下:
 

#include<iostream>
#include<string>
using namespace std;
class Student//声明基类
{
public:
    void get_1()//输入姓名及性别
    {
        cin >> name >> sex;
    }
    void display_1()//输出姓名性别
    {
        cout << "姓名:" << name << " " << "性别:" << sex << endl;
    }
private:
    string sex;
    string name;
};
class Student1 :public Student//声明派生类,继承方式为public
{
public:
    void get_2()//输入成绩学号以及姓名性别
    {
        get_1();//在派生类中调用基类的get_1函数
        cin >> score >> num;
    }
    void display_2()//输出成绩学号以及姓名性别
    {
     display_1();//在派生类中调用基类的display_1函数
        cout << "成绩:" << score << " " << "学号:" << num << endl;
    }
private:
    int score;
    int num;
};
int main()
{
    Student1 s;//定义派生类对象
    s.get_2();
    s.display_2();
    return 0;
}

5.以下表格的知识应着重理解掌握

积累成员在派生类的访问属性

基类访问属性 继承方式 派生类访问属性 private private 不可访问 public private private protected private private private public 不可访问 public public public protected public protected private protected 不可访问 public protected protected protected protected protected

 

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值