c++ 公有继承、保护继承、私有继承

首先简单介绍一下类中关键字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

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值