21xrx.com
2024-09-20 00:37:27 Friday
登录
文章检索 我的文章 写文章
C++继承和派生的代码示例
2023-07-01 16:36:08 深夜i     --     --
C++ 继承 派生 代码示例

C++是一种面向对象的编程语言,在其中,继承和派生是重要的概念。继承允许程序员可以创建一个新的类,新的类可以使用已存在类的属性和方法。而派生是在已存在类的基础上,创建新的类,且新的类拥有已存在类的所有数据和方法。

下面是C++中继承和派生的代码示例,以进一步说明这两个概念的复杂度和优势。

继承的代码示例:


#include<iostream>

using namespace std;

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(void) {

  Rectangle Rect;

  Rect.setWidth(5);

  Rect.setHeight(7);

  // 输出对象的面积

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

  return 0;

}

在上面的示例中,我们有一个类“形状”,其包含两个数据成员"width"和"height",还有两个成员函数"setWdth"和"setHeight",分别用于设置这两个成员变量的值。我们还有一个类“矩形”,通过公有继承,“矩形”类可以访问并使用“形状”类中的所有成员变量和函数,其中“矩形”类有一个函数“getArea”可以返回“矩形”类的面积。

派生的代码示例:


#include<iostream>

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;

   }

};

// 派生类 Rectangle

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;

}

在这个示例中,我们有三个类,“形状”和“针对涂漆花费的”和“矩形”两个派生类。在“矩形”类中,它是由“形状”类和“针对涂漆花费的”类派生而来的。除了使用“形状”类中的访问函数和成员变量,还增加了一个访问函数“getCost”,用于计算矩形的涂漆花费。在主函数中,我们可以看到如何使用基类派生类来调用函数和成员变量,以便得到更多有用的信息。

总之,继承和派生是C++中的重要概念,掌握它们可以让程序员更好地将类与类之间的关系组织起来,极大地提高代码的复杂度和编程效率。

  
  

评论区

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