以示例性的程序说明C++中对象、类、继承、聚合、多态、消息在程序中如何实现
时间: 2024-01-01 22:05:59 浏览: 61
以下是一个简单的示例程序,演示了C语言中对象、类、继承、聚合、多态和消息的实现:
```
#include <stdio.h>
// 定义一个基类
typedef struct {
int x;
int y;
} Point;
// 定义一个派生类
typedef struct {
Point base; // 继承Point类
int z;
} Point3D;
// 定义一个方法,用于打印Point对象
void print_point(Point *p) {
printf("(%d, %d)\n", p->x, p->y);
}
// 定义一个方法,用于打印Point3D对象
void print_point3D(Point3D *p) {
printf("(%d, %d, %d)\n", p->base.x, p->base.y, p->z);
}
int main() {
// 创建一个Point对象并调用print_point方法
Point p = {1, 2};
print_point(&p);
// 创建一个Point3D对象并调用print_point3D方法
Point3D p3d = {{3, 4}, 5};
print_point3D(&p3d);
// 将Point3D对象赋值给Point指针,实现多态
Point *p_ptr = (Point *)&p3d;
print_point(p_ptr);
return 0;
}
```
在这个示例程序中,我们定义了一个基类Point和一个派生类Point3D,Point3D类继承了Point类。我们还定义了两个方法print_point和print_point3D,用于打印Point和Point3D对象的坐标。
在main函数中,我们创建了一个Point对象p和一个Point3D对象p3d,并分别调用了print_point和print_point3D方法打印它们的坐标。注意到我们可以将Point3D对象赋值给Point指针,实现了多态,即同一个指针可以指向不同的对象。
这个示例程序还演示了对象的聚合,即Point3D对象中包含了一个Point对象作为基类。最后,我们在程序中发送了消息,即调用了print_point和print_point3D方法,这是一种对象之间通信的方式。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)