"继承与派生:类与对象的运算符重载与面积计算"
需积分: 10 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 对象,并计算各对象的面积并输出。这段代码利用了继承与派生的特性,通过定义一个基类来派生出不同的子类,实现了代码的复用和扩展。同时,利用了运算符重载,使得代码更加简洁和易读。整体而言,这段代码展示了面向对象编程的特点,体现了代码的灵活性和可扩展性。
2009-12-21 上传
2009-09-07 上传
2023-05-27 上传
2023-06-02 上传
2024-06-25 上传
2024-06-26 上传
2023-03-21 上传
2023-02-08 上传
xuehuazailuo
- 粉丝: 1
- 资源: 28
最新资源
- 开源通讯录备份系统项目,易于复刻与扩展
- 探索NX二次开发:UF_DRF_ask_id_symbol_geometry函数详解
- Vuex使用教程:详细资料包解析与实践
- 汉印A300蓝牙打印机安卓App开发教程与资源
- kkFileView 4.4.0-beta版:Windows下的解压缩文件预览器
- ChatGPT对战Bard:一场AI的深度测评与比较
- 稳定版MySQL连接Java的驱动包MySQL Connector/J 5.1.38发布
- Zabbix监控系统离线安装包下载指南
- JavaScript Promise代码解析与应用
- 基于JAVA和SQL的离散数学题库管理系统开发与应用
- 竞赛项目申报系统:SpringBoot与Vue.js结合毕业设计
- JAVA+SQL打造离散数学题库管理系统:源代码与文档全览
- C#代码实现装箱与转换的详细解析
- 利用ChatGPT深入了解行业的快速方法论
- C语言链表操作实战解析与代码示例
- 大学生选修选课系统设计与实现:源码及数据库架构