21xrx.com
2024-09-20 00:00:23 Friday
登录
文章检索 我的文章 写文章
C++类的继承方式:概述与示例分析
2023-07-03 20:46:41 深夜i     --     --
C++ 继承 概述 示例分析

C++类的继承是实现面向对象编程的重要机制之一。其通过定义一个类派生类(子类)从一个已存在的类(基类)继承成员变量和成员函数来扩展类的功能。C++类的继承方式主要有公有继承、保护继承和私有继承三种。

公有继承是最常用和基本的继承方式。在公有继承中,派生类可以访问基类的公有成员,但不能访问基类的私有成员。例如,以下代码演示了一个简单的公有继承示例:


class Shape {

  public:

   void setWidth(int w)

     width = w;

   

   void setHeight(int h)

     height = h;

   

  protected:

   int width;

   int height;

};

class Rectangle: public Shape {

  public:

   int getArea() {

     return (width * height);

   }

};

int main() {

  Rectangle Rect;

  Rect.setWidth(5);

  Rect.setHeight(7);

  cout << "Total area: " << Rect.getArea() << endl;

  return 0;

}

在以上示例中,Rectangle是派生类,从Shape基类继承setWidth和setHeight方法。在main函数中,Rect对象通过setWidth和setHeight设置width和height,然后调用getArea方法计算面积并输出。

保护继承与公有继承类似,派生类可以访问基类的保护成员,但不能访问基类的私有成员。以下是一个保护继承的示例:


class Shape

  protected:

   int width;

   int height;

;

class Rectangle: protected Shape {

  public:

   int getArea() {

     return (width * height);

   }

   void setWidth(int w)

     width = w;

   

   void setHeight(int h)

     height = h;

   

};

int main() {

  Rectangle Rect;

  Rect.setWidth(5);

  Rect.setHeight(7);

  cout << "Total area: " << Rect.getArea() << endl;

  return 0;

}

在以上示例中,Rectangle从Shape基类继承width和height成员变量,并使用setWidth和setHeight方法来设置它们的值。同样,getArea方法计算面积。

最后,私有继承是最严格的继承方式。在私有继承中,派生类可以访问基类的私有成员,但无法直接访问基类的公共成员和保护成员。以下是一个私有继承的示例:


class Shape

  private:

   int width;

   int height;

;

class Rectangle: private Shape {

  public:

   int getArea() {

     return (width * height);

   }

   void setWidth(int w)

     width = w;

   

   void setHeight(int h)

     height = h;

   

};

int main() {

  Rectangle Rect;

  Rect.setWidth(5);

  Rect.setHeight(7);

  cout << "Total area: " << Rect.getArea() << endl;

  return 0;

}

在以上示例中,Rectangle从Shape基类私有继承两个整型成员变量。由于这些成员变量是私有的,派生类的公有成员函数setWidth和setHeight必须用来设置它们的值。同样,getArea方法计算矩形的面积。

总之,C++类的继承方式可以让开发人员方便地扩展类的功能,并在程序中实现面向对象编程。公有继承、保护继承和私有继承三种方式都有其独特的用途,根据具体需求选择合适的继承方式非常重要。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复