继承

共有继承:

基类的public和protected在派生类还是public和protected。

保护继承:

基类的public和protected在派生类为protected。

私有继承:

基类的public和protected在派生类为private。

基类的private成员在派生类不可见

例如:

#include <iostream>

using namespace std;


class Base
{
public:
	Base();
	~Base();
public:
	int a;
protected:
	int b;
private:
	int c;
};

class Son:public Base
{
public:	
	Son();
	~Son();
	
	void setA1(){aa=a;}//正确
	void setA2(){aa=b;}//正确
	void setA3(){aa=c;}//错误,基类private成员在派生类不可见
	
public:
	int aa;
};


int main()
{
	return 0;
}

根据访问权限总结出不同的访问类型,如下所示: 

 访问publicprotectedprivate
同一个类yesyesyes
派生类yesyesno
外部类yesnono

 外部类只能通过共有成员函数访问类内部的成员变量,如下面例子:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

class testA
{
public:
	testA(){cout<<"gou jian"<<endl;};
	~testA(){};
	
	void setA(int ma){a=ma;}
	void setB(int mb){b=mb;}
	void setC(int mc){c=mc;}
	
public:
	int getA(){return a;}
protected:
	int getB(){return b;}
private:
	int getC(){return c;}
	
public:
	int a;
protected:
	int b;
private:
	int c;
};


int main()
{
	testA *test = new testA();
	test->setA(1);
	test->setB(2);
	test->setC(3);
	
	//在类的外部,public成员函数可用
	int aa=test->getA();
	cout<<"aa = "<<aa<<endl;
	
	//error 在类的外部,protected成员函数不可用
	int bb=test->getB();
	cout<<"bb = "<<bb<<endl;
	
	//error 在类的外部,private成员函数不可用
	int cc=test->getC();
	cout<<"cc = "<<cc<<endl;
	
	return 0;
	
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值