基本继承关系

表2.1.1 访问控制与派生关系
访问 public protected private
同一个类 yes yes yes
友元 yes yes yes
派生类 yes yes no
外部类 yes no no

公有继承(public):当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问。 保护继承(protected): 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员。 私有继承(private):当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员。


多重继承

二义性问题

在多重继承中,需要解决的主要问题是标识符不唯一,即二义性问题。例如,当在派生类继承的多个基类中有同名成员时,派生类中就会出现标识不唯一(二义性)的情况,这在程序中是不允许的。

代码清单 2.1.1 二义性错误
  1. #include <iostream>
  2. #include <string.h>
  3. #include <unistd.h>
  4. using namespace std;
  5. class Sofa
  6. {
  7. private:
  8. int weight;
  9. public:
  10. void watchTV(void) { cout << "watch TV" << endl; }
  11. void setWeight(int weight) { this->weight = weight; }
  12. int getWeight(void) const { return weight; }
  13. };
  14. class Bed
  15. {
  16. private:
  17. int weight;
  18. public:
  19. void sleep(void) { cout << "sleep" << endl; }
  20. void setWeight(int weight) { this->weight = weight; }
  21. int getWeight(void) const { return weight; }
  22. };
  23. class Sofabed : public Sofa, public Bed
  24. {
  25. };
  26. int main(int argc, char **argv)
  27. {
  28. Sofabed s;
  29. s.watchTV();
  30. s.sleep();
  31. s.setWeight(100);
  32. return 0;
  33. }

编译时报错:

36:7: error: request for member ‘setWeight’ is ambiguous s.setWeight(100);

提示setWeight 是被多重定义,编译器因此无法确定使用哪个父类的函数

二义性解决方案
  • 使用作用域运算符 ::
  • 使用同名覆盖 overwrite
  • 使用虚基类 virtual
    作用域运算符
      s.Sofa::setWeight(100);
    
    这样就指定了要使用的基类函数
    同名覆盖
    使用了C++的就近原则,重新定义一个与基类同名的成员和成员函数,从而迫使编译器引用派生类的成员
    class Sofabed : public Sofa, public Bed
    {
    private:
      int weight;
    public:
      void setWeight(int weight) { this->weight = weight; }
      int getWeight(void) const { return weight; }
    };