公有继承:
#include<bits/stdc++.h>using namespace std;/*** 公有继承* */class A{public:int x;void set_z(int i) {z = i;}int get_z() {return z;}protected:int y;private:int z;};class B: public A {public:int m;void set_value(int a, int b, int c, int d, int e, int f) {x = a; // B 中的x为公有y = b; // B 中的y为保护set_z(c); // 调用基类的公有成员函数为z赋值// z = c; // 错误,B 中的z不可访问m = d;n = e;p = f;}void display() {cout<<"x="<<x<<endl; // B 中的x为公有cout<<"y="<<y<<endl; // B 中的y为保护// cout<<"z="<<z<<endl; // 错误,B 中的z不可访问cout<<"z="<<get_z()<<endl; // 调用基类的公有成员函数获得z的值cout<<"m="<<m<<endl; // 公有cout<<"n="<<n<<endl; // 保护cout<<"p="<<p<<endl; // 私有}protected:int n;private:int p;};int main() {B obj;obj.set_value(1, 2, 3, 4, 5, 6);obj.display();cout<<"x="<<obj.x<<endl; // B 中的x为公有// cout<<"y="<<obj.y<<endl; // B 中的y为保护,无法通过对象访问// cout<<"z="<<obj.z<<endl; // B 中的z不可访问cout<<"m="<<obj.m<<endl; // 公有// cout<<"n="<<obj.n<<endl; // 保护,无法通过对象访问// cout<<"p="<<obj.p<<endl; // 私有return 0;}
私有继承:
#include<bits/stdc++.h>using namespace std;/*** 私有继承* */class A{public:int x;void set_z(int i) {z = i;}int get_z() {return z;}protected:int y;private:int z;};class B: private A {public:int m;void set_value(int a, int b, int c, int d, int e, int f) {x = a; // B 中的x为私有y = b; // B 中的y为私有set_z(c); //// z = c; // 错误,B 中的z不可访问m = d;n = e;p = f;}void display() {cout<<"x="<<x<<endl; // B 中的x为私有cout<<"y="<<y<<endl; // B 中的y为私有// cout<<"z="<<z<<endl; // 错误,B 中的z不可访问cout<<"z="<<get_z()<<endl; // 调用基类的公有成员函数获得z的值cout<<"m="<<m<<endl; // 公有cout<<"n="<<n<<endl; // 保护cout<<"p="<<p<<endl; // 私有}protected:int n;private:int p;};int main() {B obj;obj.set_value(1, 2, 3, 4, 5, 6);obj.display();// cout<<"x="<<obj.x<<endl; // B 中的x为私有// cout<<"y="<<obj.y<<endl; // B 中的y为私有// cout<<"z="<<obj.z<<endl; // B 中的z不可访问cout<<"m="<<obj.m<<endl; // 公有// cout<<"n="<<obj.n<<endl; // 保护,无法通过对象访问// cout<<"p="<<obj.p<<endl; // 私有return 0;}
保护继承:
#include<bits/stdc++.h>using namespace std;/*** 保护继承* */class A{public:int x;void set_z(int i) {z = i;}int get_z() {return z;}protected:int y;private:int z;};class B: private A {public:int m;void set_value(int a, int b, int c, int d, int e, int f) {x = a; // B 中的x为保护y = b; // B 中的y为保护set_z(c); //// z = c; // 错误,B 中的z不可访问m = d;n = e;p = f;}void display() {cout<<"x="<<x<<endl; // B 中的x为保护cout<<"y="<<y<<endl; // B 中的y为保护// cout<<"z="<<z<<endl; // 错误,B 中的z不可访问cout<<"z="<<get_z()<<endl; // 调用基类的公有成员函数获得z的值cout<<"m="<<m<<endl; // 公有cout<<"n="<<n<<endl; // 保护cout<<"p="<<p<<endl; // 私有}protected:int n;private:int p;};int main() {B obj;obj.set_value(1, 2, 3, 4, 5, 6);obj.display();// cout<<"x="<<obj.x<<endl; // B 中的x为保护// cout<<"y="<<obj.y<<endl; // B 中的y为保护// cout<<"z="<<obj.z<<endl; // B 中的z不可访问cout<<"m="<<obj.m<<endl; // 公有// cout<<"n="<<obj.n<<endl; // 保护,无法通过对象访问// cout<<"p="<<obj.p<<endl; // 私有return 0;}
运行的结果和私有继承一样
但是私有继承会中断继承
