C++中的继承问题

来源:互联网 发布:mac os 和win10双系统 编辑:程序博客网 时间:2024/06/06 02:49


C++中的继承问题

在《程序员面试宝典》(第4版)中讲到“在私有继承时,基类的成员只能由直接派生类访问,而无法再往下继承。”认为是正确的。

eg:

#include<iostream>
using namespace std;
class A{
protected:
 int a;
};
class B:private A{};
class C :public B
{
public:
 void fun() {
  a = 520;
  cout << "a=" << a << endl;
 }
};
int main(void)
{
 C c;
 c.fun();

 return 0;
}
//c=520

当B为private 继承时,基类成员不再由B的派生类继续继承,即不论public为何种方式,C类都不会基类成员

Compile会有error C2247: 'a' not accessible because 'B' uses 'private' to inherit from 'A'


书上说“若在保护继承时,基类的成员也只能由直接派生类访问,而无法再往下继承。”,认为此说法不正确。

eg:

#include<iostream>
using namespace std;
class A{
protected:
 int a;
};
class B:protected A{};
class C :private B
{
public:
 void fun() {
  a = 520;
  cout << "a=" << a << endl;
 }
};
int main(void)
{
 C c;
 c.fun();

 return 0;
}
//c=520

B类的派生类C可继承访问基类A类中的成员。


保护继承与私有继承类似,继承之后的类相对于基类来说是独立的。保护继承的类对象,在公开场合同样不能使用基类的成员。

eg:

#include<iostream>
using namespace std;

class Animal{
public:
 Animal(){}
 void eat(){cout<<"eat\n";}
};
class Giraffe: protected Animal
{
public:
 Giraffe(){}
 void StrechNeck()
 {cout<<"strech neck \n";}
 void take()
 {
  eat();//OK
 }
};

void main(){
 Giraffe gir;
// gir.eat();//error
 gir.take();  //OK
 gir.StrechNeck();
}



0 0