"继承与派生:类与对象的运算符重载与面积计算"

需积分: 10 4 下载量 109 浏览量 更新于2023-12-27 1 收藏 163KB DOC 举报
```C++ #include <iostream> using namespace std; // 定义 Point 类 class Point { protected: int x, y; public: Point(int xx = 0, int yy = 0) : x(xx), y(yy) {} int getX() { return x; } int getY() { return y; } }; // 派生 Rectangle 类 class Rectangle : public Point { protected: int width, height; public: Rectangle(int xx = 0, int yy = 0, int w = 0, int h = 0) : Point(xx, yy), width(w), height(h) {} int area() { return width * height; } }; // 派生 Circle 类 class Circle : public Point { private: int radius; public: Circle(int xx = 0, int yy = 0, int r = 0) : Point(xx, yy), radius(r) {} float area() { return 3.14 * radius * radius; } }; int main() { Rectangle rect(1, 2, 3, 4); Circle cir(1, 2, 5); cout << "Rectangle Area: " << rect.area() << endl; cout << "Circle Area: " << cir.area() << endl; return 0; } ``` 以上是一个用C++编写的程序,其中定义了一个 Point 类,并派生出了 Rectangle 类和 Circle 类。在主函数中创建了一个 Rectangle 对象和一个 Circle 对象,并计算各对象的面积并输出。这段代码利用了继承与派生的特性,通过定义一个基类来派生出不同的子类,实现了代码的复用和扩展。同时,利用了运算符重载,使得代码更加简洁和易读。整体而言,这段代码展示了面向对象编程的特点,体现了代码的灵活性和可扩展性。