0
点赞
收藏
分享

微信扫一扫

公用继承


一.准备知识

  首先我们需要知道以下几个重要的概念:

  1. 基类
  2. 派生类
  3. 公用基类
  4. 公用派生类

概念引例

已知一个类​​Student​​,作用为用户输入学生的学号,姓名,性别,最后显示在屏幕上:[代码如下]

class Student
{
public:
void get_value()
{
cin >> num >> name >> sex;
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl;
}
private:
int num;
string name;
char sex;
};

但现在我们又有新的需求,我们想要补充一些信息进入类里,为了防止代码的冗长和保持代码隐蔽性,安全性,我们决定在类A外想办法进行信息的补充。
  我们现在想让用户除了输入以上信息之外能够再输入学生的年龄,家庭地址。
  所以我们又新建一个类​​​Student1​​:

class Student1 :public Student
{
public:
void get_value_1()
{
cin >> age >> addr;
}
void display_1()
{
cout << "age=" << age << endl;
cout << "addr=" << addr << endl;
}
private:
int age;
string addr;
};

这时候我们回过来理解刚才给出的概念:

  1. 基类--------------------------------------->​​Student​​类
  2. 派生类--------------------------------------->​​Student1​​类

   我们用Student1类的数据来补充Student类的信息时,还要保留

Student类里的数据,我们把这种保留机制称为​​继承​​。

  继承方式有两种:​​public​​​和​​private​​。我们这里讲到的是公用继

承,也就是​​public​​继承。所以概念理解:

  1. 公用基类--------------------------------------->​​Student​​类
  2. 公用派生类--------------------------------------->​​Student1​​类

二.公用继承的定义

我们在以上代码中已经提到过,这里直接给出定义的代码:

class Student1 :public

代码的示意:为​​基类Student​​​定义一个​​公用的派生类Student1​

反之,我们也可以定义一个私用的派生类,也就是私用继承,如下定义:

class Student1 :private

私用继承后边我们会讲到。

三.完成代码

/*================================
函数功能:利用公有继承输出学生信息
作者:令狐荣豪
时间:2019/5/19
==================================*/
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
void get_value()
{
cin >> num >> name >> sex;
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl;
}
private:
int num;
string name;
char sex;
};

class Student1 :public Student
{
public:
void get_value_1()
{
cin >> age >> addr;
}
void display_1()
{
cout << "age=" << age << endl;
cout << "addr=" << addr << endl;
}
private:
int age;
string addr;
};
int main()
{
Student1 stud;
stud.get_value();
stud.get_value_1();
stud.display();
stud.display_1();
return 0;
}

四.输出结果

公用继承_数据


举报

相关推荐

0 条评论