//Shape.h #pragma once

/定义一个抽象图形类 Shape,定义纯虚函数 area() 和 perim() 用以计算面积和周长。 从 Shape 派生出矩形(Rectangle)、圆形(Circle)具体派生类。 程序中通过基类指针(//纯虚析构)来调用派生类对象中的重写的纯虚函数 计算不同形状对象的面积和周长。/

//抽象图形类 class Shape { public: virtual double area(void) = 0; virtual double perim(void) = 0;

};

// Rectangle.h #pragma once #include "Shape.h"

/定义一个抽象图形类 Shape,定义纯虚函数 area() 和 perim() 用以计算面积和周长。 从 Shape 派生出矩形(Rectangle)、圆形(Circle)具体派生类。 程序中通过基类指针(//纯虚析构)来调用派生类对象中的重写的纯虚函数 计算不同形状对象的面积和周长。/

class Rectangle :public Shape { private: double length; //矩形的长 double width; //矩形的宽 public: Rectangle(double length, double width){ this->length = length; this->width = width; } virtual double area(void) { return length * width; } virtual double perim(void) { return 2 * (length + width); } };

//Main.cpp #include #include "Shape.h" #include "Revtangle.h" using namespace std;

int main() { int length = 2, wide = 5; Shape* ob = new Rectangle(length, wide); cout << ob->area(); delete ob; return 0; }

C++ 抽象图形类 Shape 及其派生类 Rectangle 的实现

原文地址: https://www.cveoy.top/t/topic/npio 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录