#ifndef SHAPE_H | |
#define SHAPE_H | |
class Shape { | |
public: | |
virtual ~Shape() {} | |
virtual double area() const = 0; // 纯虚函数,使得Shape成为抽象类 | |
}; | |
#endif // SHAPE_H |
#ifndef CIRCLE_H | |
#define CIRCLE_H | |
#include "Shape.h" | |
class Circle : public Shape { | |
public: | |
Circle(double radius); | |
double area() const override; // 重写Shape类中的纯虚函数 | |
private: | |
double radius; | |
}; | |
#endif // CIRCLE_H |
#include "Circle.h" | |
#include <cmath> | |
Circle::Circle(double radius) : radius(radius) {} | |
double Circle::area() const { | |
return M_PI * radius * radius; | |
} |
#ifndef RECTANGLE_H | |
#define RECTANGLE_H | |
#include "Shape.h" | |
class Rectangle : public Shape { | |
public: | |
Rectangle(double width, double height); | |
double area() const override; // 重写Shape类中的纯虚函数 | |
private: | |
double width, height; | |
}; | |
#endif // RECTANGLE_H |
#include "Rectangle.h" | |
Rectangle::Rectangle(double width, double height) : width(width), height(height) {} | |
double Rectangle::area() const { | |
return width * height; | |
} |
#include <iostream> | |
#include "Circle.h" | |
#include "Rectangle.h" | |
int main() { | |
Circle circle(5.0); // 创建一个半径为5的圆 | |
std::cout << "Circle area: " << circle.area() << std::endl; // 输出圆的面积 | |
Rectangle rectangle(4.0, 6.0); // 创建一个4x6的矩形 | |
std::cout << "Rectangle area: " << rectangle.area() << std::endl; // 输出矩形的面积 | |
return 0; | |
} |
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) | Powered by Discuz! X3.4 |