C++ 设计模式 聚合 C++代码示例
时间: 2023-04-03 20:04:49 浏览: 94
我可以回答这个问题。C 设计模式中的聚合是指将多个对象组合成一个更大的对象,这个更大的对象可以像单个对象一样被使用。下面是一个 C 代码示例:
```c
#include <stdio.h>
// 定义一个结构体表示一个点
typedef struct {
int x;
int y;
} Point;
// 定义一个结构体表示一个矩形
typedef struct {
Point topLeft;
Point bottomRight;
} Rectangle;
// 计算矩形的面积
int calculateArea(Rectangle rect) {
int width = rect.bottomRight.x - rect.topLeft.x;
int height = rect.bottomRight.y - rect.topLeft.y;
return width * height;
}
int main() {
// 创建两个点
Point p1 = {0, 0};
Point p2 = {5, 5};
// 创建一个矩形,包含这两个点
Rectangle rect = {p1, p2};
// 计算矩形的面积
int area = calculateArea(rect);
// 输出结果
printf("The area of the rectangle is %d\n", area);
return 0;
}
```