给我一个C++使用多继承的例子
时间: 2024-04-29 12:22:36 浏览: 17
好的,这是一个使用多继承的例子:
```c
#include <stdio.h>
/* 定义一个基类:Shape */
typedef struct {
double x;
double y;
} Shape;
/* 定义一个 Rectangle 类,继承 Shape */
typedef struct {
Shape shape;
double width;
double height;
} Rectangle;
/* 定义一个 Circle 类,继承 Shape */
typedef struct {
Shape shape;
double radius;
} Circle;
/* 定义一个包含两个父类的类 Square,继承 Rectangle 和 Circle */
typedef struct {
Rectangle rectangle;
Circle circle;
} Square;
int main() {
/* 创建一个 Square 对象 */
Square square = {
{{1, 2}, 3, 4},
{{5, 6}, 7}
};
/* 打印 Square 对象的属性 */
printf("Square x: %f, y: %f\n", square.rectangle.shape.x, square.rectangle.shape.y);
printf("Square width: %f, height: %f\n", square.rectangle.width, square.rectangle.height);
printf("Square radius: %f\n", square.circle.radius);
return 0;
}
```
这个例子中,我们定义了三个类:Shape、Rectangle 和 Circle。Rectangle 和 Circle 都继承自 Shape,Square 则继承自 Rectangle 和 Circle。通过这种方式,Square 可以使用 Rectangle 和 Circle 的所有方法和属性,同时还有自己独有的属性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)