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