#P2236. 语法知识.面向对象编程.2
语法知识.面向对象编程.2
学习重点:
-
概念和属于:{基类、派生类},{父类,子类},继承
-
通过 公有继承方式(public)的继承(这是最基本最简单的继承)
- 父类中的 pubilic 成员,在 子类中仍为 public
- 父类中的 private 成员,在子类中仍为 priviate
- 父类中的 protected 成员,在子类中仍为 protected
-
调用父类的构造函数
-
在子类中访问父类的成员变量和成员函数
-
在实例对象中访问父类的成员变量和成员函数
#include<bits/stdc++.h>
using namespace std;
// 定义一个叫 Student 的类
class Student{
public:
string name;
char gander; // ‘F’ 是女, ‘M’ 是男
Student(string a, char b, int c){
this->name = a;
this->gander = b;
this->set_score(c);
};
// 没有成绩信息的构造函数
Student(string a, char b):name(a),gander(b){}; // 这里用了一种新的语法
Student(){ }; // 如果没有参数,啥事都不做
void set_score(int a){
this->score = a;
}
void ask_score(){
// 询问成绩,成员函数是可以访问 private 成员的
cout<<"I am "<<this->name<<".";
// 假设成绩数据很敏感,人家不想告诉你具体多少分,只是告诉你大概情况
if(this->score >= 90)
printf("I am perfect.\n");
else if(this->score >= 80)
printf("I am good.\n");
else if(this->score>=60)
printf("I am not bad.\n");
else
printf("I don't want to tell you anything.\n");
};
private:
int score; // 成绩是不想给别人轻易访问,设置为 private 属性
};
// 定义一个叫 IT_Student 的类,它是从 Student 类派生出来的
// 两者关系: Student 类叫“父类”, IT_Student 类叫“子类”
// 另外一种说法: Student 类叫“基类”, IT_Student 类叫“派生类”
// 在“继承”的过程中,父类的“资产”(成员变量和成员方法)会被子类继承(简单来说:父亲有的东西,儿子自然就有了,实际上情况会复杂很多,后面会逐步讲述)
class IT_Student:
public Student // 这里的 public 意思是“公有继承”,除了 public 继承之外,还要 protected 和 private 继承,以后再讲
{
public:
string language;
// 调用父类的构造函数必须用下面这种格式
IT_Student(string a,char b,int c,string d):Student(a,b,c){
this->language = d;
};
void ask_IT(){
cout<<"I am learning "<<this->language<<" programing.\n";
this->ask_score(); // 在子类调用父类的方法
};
};
int main(){
Student a("张三",'M',91);
a.ask_score();
// a 只是一名普通学生,它没有信息学学生类的专有信息
//a.ask_IT(); 这会报错的
IT_Student b("杨君",'M',95,"C++");
b.ask_IT();
// 也可以在从实例直接调用父类的方法
IT_Student c("钱红",'F',75,"Python");
c.ask_score();
return 0;
}