首先简单介绍一下类中关键字protect的使用:对于基类中protected的成员,其定义的类的内部可以访问;类的使用者,即实例化的类的对象不能直接访问;类的派生类成员可以访问。
公有继承:基类成员在派生类中的成员属性不会变化,可访问基类中的public成员和protect成员,不能直接访问基类中的private成员,但可通过共有成员函数访问。
#include<iostream>
using namespace std;
//基类
class base{
int x;
public:
void setx(int n){ x=n; }
int getx(){ return x; }
void showx() { cout<<x<<endl; }
};
//派生类
class derived:public base{
int y;
public:
void sety(int n) { y=n; }
void sety() { y=getx(); }
void showy() { cout<<y<<endl; }
};
//派生类不可直接访问基类的private成员,可通过基类的共有成员函数访问
int main()
{
derived obj;
obj.setx(10);
obj.sety(20);
obj.showx();
obj.showy();
obj.sety();
obj.showx();
obj.showy();
system("pause");
}
保护继承:基类的public成员在派生类中会变成protected成员,基类的protected和private成员在派生类中保持原来的访问权限。
#include <iostream>
using namespace std;
class Base{
int x;
protected:
int getx(){ return x; }
public:
void setx(int n){ x=n; }
void showx(){ cout<<x<<endl; }
};
class Derived:protected Base{
int y;
public:
void sety(int n){ y=n; }
void sety(){ y=getx();} //访问基类的保护成员
void showy(){ cout<<y<<endl; }
};
int main(){
Derived obj;
// obj.setx(10); //错误
obj.sety(20);
// obj.showx(); //错误,
obj.showy();
system("pause");
}
私有继承:基类的中的public成员在派生类中是private, private成员在派生类中不可访问。
#include <iostream>
using namespace std;
class Base{
int x;
public:
void setx(int n){x=n; }
int getx(){return x; }
void showx(){cout<<x<<endl; }
};
class derived:private Base{
int y;
public:
void sety(int n){y=n; }
void sety(){ y=getx(); }
void showy() { cout<<y<<endl; }
};
int main(){
derived obj;
obj.setx(10);//cannot access
obj.sety(20);
obj.showx();//cannot access
obj.showy();
}
本文参照GitHub中的资料稍微整合一下,方便对比阅读,参考网址https://github.com/Light-City/CPlusPlusThings