C++继承


一、继承的定义

1.继承指的是:我们依据另一个类来定义类;当创建类时,不需要重新编写新的数据成员和成员函数,只需指定新建的类继承了一个已有的类的成员即可。

这个已有的类称为基类,新建的类称为派生类

2.继承的好处:这使得创建和维护一个应用程序变得更容易,也达到了重用代码功能和提高执行效率的效果。

例如,哺乳动物是动物,狗是哺乳动物,因此,狗是动物,等等

               

// 基类
class Animal {
    // eat() 函数
    // sleep() 函数
};


//派生类
class Dog : public Animal {
    // bark() 函数
};

二、基类、派生类的访问限制

派生类可以访问基类中所有的非私有成员,声明为 private的成员不能被派生类的成员函数访问

一个派生类继承了所有的基类方法,但下列情况除外:

  • 基类的构造函数、析构函数和拷贝构造函数。
  • 基类的重载运算符。
  • 基类的友元函数。

三、派生类的类型

当一个类派生自基类,该基类可以被继承为 public、protected 或 private 几种类型

我们几乎不使用 protected 或 private 继承,通常使用 public 继承

四、继承类型

1.公有继承(public):当一个类派生自公有基类时

基类的公有成员也是派生类的公有成员

基类的保护成员也是派生类的保护成员

基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问

2.保护继承(protected): 当一个类派生自保护基类时

基类的公有和保护成员将成为派生类的保护成员

3.私有继承(private):当一个类派生自私有基类时

基类的公有和保护成员将成为派生类的私有成员

五、多继承

一个子类可以有多个父类,它继承了多个父类的特性

实例:

#include 
 
using namespace std;
 
// 基类 Shape
class Shape 
{
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }
   protected:
      int width;
      int height;
};
 
// 基类 PaintCost
class PaintCost 
{
   public:
      int getCost(int area)
      {
         return area * 70;
      }
};
 
// 派生类
class Rectangle: public Shape, public PaintCost
{
   public:
      int getArea()
      { 
         return (width * height); 
      }
};
 
int main(void)
{
   Rectangle Rect;
   int area;
 
   Rect.setWidth(5);
   Rect.setHeight(7);
 
   area = Rect.getArea();
   
   // 输出对象的面积
   cout << "Total area: " << Rect.getArea() << endl;
 
   // 输出总花费
   cout << "Total paint cost: $" << Rect.getCost(area) << endl;
 
   return 0;
}

当上面的代码被编译和执行时,它会产生下列结果:

Total area: 35
Total paint cost: $2450
 
C++