您的位置:首页 > 其它

区分“派生类对象”和“派生类”对基类成员的访问权限

2014-08-13 17:25 267 查看
1.“派生类对象”对基类成员的访问权限

对于共有继承,只有基类中的共有成员能被“派生类对象”访问,保护和私有成员不能被“派生类对象”访问。

对于私有和保护继承,基类中的所有成员不能被“派生类对象”访问

2. “派生类”对基类成员的访问权限

对于共有继承,基类中的共有和保护成员能被“派生类”访问,私有成员不能被“派生类”访问。

对于私有和保护继承,也是基类中的共有和保护成员能被“派生类”访问,私有成员不能被“派生类”访问。

通过下面代码说明派生类私有继承和共有继承:

#include <iostream>

using namespace std;

class Animal

{

public:

 Animal(){}

 void eat()

 {

  cout<<"eat."<<endl;

 }

};

class Giraffe:private Animal

{

public:

 Giraffe(){}

 void StrchNeck(double)

 {

  cout<<"strech neck"<<endl;

 }

 void take()

 {

  eat();   //派生类访问基类

 }

};

class Cat:public Animal

{

public:

 Cat(){}

 void Meaw()

 {

  cout<<"meaw"<<endl;

 }

};

void Func(Animal &an)

{

 an.eat();

}

void Func1(Giraffe &an)

{

 an.take(); //先访问本类成员函数,本类成员函数再访问基类成员函数

}

void main()

{

 Cat dao;

 Giraffe gir;

 Func(dao);//共有继承,Griaffe类对象能访问Animal类所有的共有成员

// Func(gir); //error Griaffe私有继承了Animal,Griaffe类对象不能直接访问Animal类所有的成员

 Func1(gir);

}

 

 

 

 

 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: