21-22.关于类的继承与派生

来源:互联网 发布:淘宝9秒视频制作软件 编辑:程序博客网 时间:2024/05/16 04:59
#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;}

多继承

#include <iostream> using namespace std; // 基类 Shapeclass Shape {   public:      void setWidth(int w)      {         width = w;      }      void setHeight(int h)      {         height = h;      }   protected:      int width;      int height;}; // 基类 PaintCostclass 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;}