类在继承时会遵循以下几点
- 基类的private集在子类中是不可访问的
- 如果以public级别继承,则基类的protected集和public集在子类中级别不变
- 如果以protected级别继承,则基类的public集会并入子类的protected集的一部分,protected集则直接并入子类的protected集
- 如果以private级别继承,则基类的public集和protected集都会并入子类的private集
- 可以用using指令让可见的基类成员集在子类中进行访问级别转换
测试用例
#include<iostream>
using namespace std;
//基类
class People{
public:
void setName(char *name);
void setAge(int age);
char *getName();
int getAge();
private:
char *myName;
int myAge;
};
void People::setName(char *name) {myName = name;}
void People::setAge(int age) {myAge = age;}
char* People::getName() {return myName;}
int People::getAge() {return myAge;}
//public继承子类
class Student: public People{
public:
void setScore(float score);
float getScore();
void readStudent(ostream& os, Student& stu){
this->read(os);
}
protected:
float myScore;
ostream& read(ostream& os){
os << this->getName() << "'s age is " << this->getAge() << ",and the score is " << this->getScore() << endl;
return os;
}
};
void Student::setScore(float score){ myScore = score; }
float Student::getScore(){ return myScore; }
class Individual:public Student{
public:
void setRank(int rank);
public:
using Student::myScore;//转换为public级别
private:
using People::myAge;//转换为private级别
private:
int my_rank;
};
void Individual::setRank(int rank) {my_rank = rank;}
//经过两级的public继承,原先的Person类的public集在Individual中仍然是public级别的
//动作单词开头小写,名词开头大写
int main(){
Student stu;
stu.setName("小明");
stu.setAge(18);
stu.setScore(95.2f);
stu.readStudent(cout,stu);
return 0;
}
总结
- 继承的级别是子类成员访问基类成员的最高权限,也是基类的成员集在并入子类的成员集时的最高级别,比如以protected级别继承,则基类的成员集并入子类的成员集时最多只会并入子类的protected集
- 不管继承方式如何,基类中的 private 成员在派生类中始终不能访问
- 要想访问基类的private集,只能通过基类的public集来实现