- //继承
- #include
- #include
- using namespace std;
- // 基类people
- class people {
- private:
- int number;
- string name;
- int age;
- protected:
- void fun();
- public:
- people(int num, string n, int a);
- ~people() { cout << "people类被析构" << endl; }
- void getpeople();
- };
- people::people(int num, string n, int a) {
- this->number = num;
- this->name = n;
- this->age = a;
- }
- void people::getpeople() {
- cout << "number:" << this->number << "name:" << this->name << "age:" << this->age << endl;
- }
- void people::fun() {
- cout << "This is people protected" << endl;
- }
- // 公有继承
- // 基类公有和保护成员的访问属性在派生类中不变
- class student : public people{
- private:
- int grade;
- protected:
- void fun2();
- public:
- student(int grade, int num, string name, int a);
- ~student();
- void getstudent();
- };
- void student::fun2() {
- this->fun(); // 访问基类保护类成员
- cout << "This is student protected" << endl;
- }
- student::student(int grade, int num, string name, int a) : grade(grade), people(num, name, a) {}
- student::~student() {
- cout << "student 类被析构" << endl;
- //不用手动调用基类析构函数,系统会自己调用
- }
- void student::getstudent() {
- this->getpeople(); // 访问基类公有成员
- cout << "grade:" << this->grade << endl;
- }
- // 保护继承
- // 基类公有成员和保护成员都以保护成员身份出现在派生类中,基类私有成员不可直接被派生类访问
- // 派生类可以访问保护类,外部使用者无法访问
- class teacher :protected people {
- private:
- int year;
- protected:
- void fun3() { cout << "This is teacher protected"; };
- public:
- teacher(int year, int num, string name, int a) :year(year), people(num, name, a) {}
- ~teacher() { cout << "teacher类被析构" << endl;; }
- void getteacher();
- };
- void teacher::getteacher() {
- this->getpeople(); //调用基类继承而来保护类
- // this->fun(); 可以
- cout << "year:" << year << endl;
- }
-
- //私有继承
- //基类公有和保护成员以派生类私有成员身份出现,只能被派生类访问
- //与保护继承的异同
- //同:都只能被派生类访问,不能被外部成员访问
- //异:派生类作为基类继续派生时,私有成员会被隐藏,不能被派生类的派生类访问,但是公有成员可以
- class college :private people {
- private:
- int score;
- protected:
- int fun4() { cout << "This is college protected" << endl; }
- public:
- college(int score, int num, string name, int a) :score(score), people(num, name, a) {}
- ~college() { cout << "college 类被析构" << endl; }
- void getcollege();
- };
- void college::getcollege() {
- this->getpeople(); //访问继承来的私有成员
- cout << "score:" << score << endl;
- }
-
- int main() {
- student zhang(3, 1, "xiaozhang", 18);
- zhang.getpeople(); //外部访问由基类公有继承而来的派生类公有成员
- zhang.getstudent(); //访问派生类的公有成员
- // zhang.fun(); 不可访问保护类成员(由基类公有继承而来)
- // zhang.fun2(); 类外不能访问保护类成员
- teacher yi(10, 2, "xiaoyi", 22);
- yi.getteacher(); //派生类公有
- // yi.fun3(); 不能调用派生类保护成员
- // yi.getpeople(); 不能调用基类保护继承来的保护成员
- college xing(100, 3, "xiaoxing", 19);
- xing.getcollege(); //自己的公有成员
- // xing.getpeople(); //不能访问继承来的私有成员
- return 0;
- }