C++基础——继承与派生

三种继承方式
 基类      public     protected     private 


公共继承   public     protected      不可见
保护继承   protected  protected      不可见
私有继承   private    private        不可见


1、对于公有继承方式

(1) 基类成员对其对象的可见性:

公有成员可见,其他不可见。这里保护成员同于私有成员。

(2) 基类成员对派生类的可见性:

公有成员和保护成员可见,而私有成员不可见。这里保护成员同于公有成员。

(3) 基类成员对派生类对象的可见性:

公有成员可见,其他成员不可见。

所以,在公有继承时,派生类的对象可以访问基类中的公有成员;
派生类的成员函数可以访问基类中的公有成员和保护成员。
这里,一定要区分清楚派生类的对象和派生类中的成员函数对基类的访问是不同的。


2、对于私有继承方式
(1) 基类成员对其对象的可见性:

公有成员可见,其他成员不可见。

(2) 基类成员对派生类的可见性:

公有成员和保护成员是可见的,而私有成员是不可见的。

(3) 基类成员对派生类对象的可见性:

所有成员都是不可见的。
所以,在私有继承时,基类的成员只能由直接派生类访问,而无法再往下继承。

3、对于保护继承方式
这种继承方式与私有继承方式的情况相同。两者的区别仅在于对派生类的成员而言,对基类成员有不同的可见性。
上述所说的可见性也就是可访问性。

关于可访问性还有另的一种说法。这种规则中,称派生类的对象对基类访问为水平访问,
称派生类的派生类对基类的访问为垂直访问。


注意:
派生类的对象访问时,属于外部访问。

派生类的成员函数是内部的。

-------------

#include<iostream>
using namespace std;
class A
{
public:
	void f1()
	{
		cout<<"A.f1()..."<<endl;
	}
	void display()
	{  
	   cout<<" -----display()-----"<<endl;
       cout<<"i= "<<i<<endl;
	   cout<<"j= "<<j<<endl;
	   cout<<"k= "<<k<<endl;
	   f1();
	   f22();
	   cout<<" -----display()-----"<<endl;
	}
	int i;
protected:
	void f2()
	{
		cout<<"A.f2()..."<<endl;
	}
	int j;
private:
void f22()
	{
		cout<<"A.f22()..."<<endl;
	}
	int k;
};

class B:public  A
{
public:
	void f3()//
	{   f1();
	    f2();
	//	f22();子类的成员函数不能调用父类的私有成员函数。
		cout<<"B.f3()..."<<endl;
	}
	void show()
	{ 
	 
	  cout<<" -----show()-----"<<endl;
	  display();
	  cout<<"m= "<<m<<endl;
	  cout<<"n= "<<n<<endl;
	  f3();
	 cout<<" -----show()-----"<<endl;
	}
protected:
	int m;
private:
	int n;
};

class C:public  B
{
public:
	void f4()
	{   
		f1();
		f2();
		f3();
		cout<<"C.f4()..."<<endl;
	}
	void display_all()
	{
		
	cout<<" -----display_all()-----"<<endl;
/*    
     cout<<"i= "<<i<<endl;
	  cout<<"j= "<<j<<endl;
	 // cout<<"k= "<<k<<endl;私有成员不能访问。
	  cout<<"m= "<<m<<endl;
	 // cout<<"n= "<<n<<endl;私有成员不能访问。
*/   
	 show();
     cout<<"p= "<<p<<endl;
	 f4();
	 cout<<" -----display_all()-----"<<endl;
	}

private:
	int p;
};
int main()
{
	A a1;
	B b1;
	C c1;

    b1.i=1;//子类对象可以修改父类的public数据成员。
	cout<<"b1.i= "<<b1.i<<endl;
	//cout<<"b1.j"<<b1.j<<endl;外部protected、private都不可以引用。
	//cout<<"b1.k"<<b1.k<<endl;外部protected、private都不可以引用。

	b1.f3();//子类的成员函数能调用父类的成员函数。public、protected。

	b1.f1();//父类的public可以访问。
  //b1.f2();外部protected、private都不可以访问。
cout<<"c1.i= "<<c1.i<<endl;
 /* cout<<"c1.m= "<<c1.m<<endl;
    cout<<"c1.n= "<<c1.n<<endl;
    cout<<"c1.j= "<<c1.j<<endl;外部不能引用基类的保护成员。
    cout<<"c1.k= "<<c1.k<<endl;外部不能引用基类私有成员。
    cout<<"c1.i= "<<c1.p<<endl;外部不能引用私有成员。
*/
 
	a1.display();
 	b1.show();
    c1.display_all();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值