c++ 中interface用法
时间: 2023-12-01 22:02:36 浏览: 76
C语言中没有内置的interface关键字,因此不能直接定义interface。但是可以通过结构体指针和函数指针实现类似interface的功能。以下是一个例子:
```c
// 定义一个接口
typedef struct {
void (*do_something)(void);
} MyInterface;
// 定义一个实现接口的结构体
typedef struct {
MyInterface interface;
int data;
} MyStruct;
// 实现接口函数
void do_something_impl(void) {
printf("Doing something!\n");
}
int main() {
MyStruct my_struct = { { do_something_impl }, 42 };
// 调用实现的接口函数
my_struct.interface.do_something();
return 0;
}
```
在这个例子中,通过定义一个MyInterface结构体和一个函数指针,实现了类似interface的功能。然后定义一个实现接口的结构体MyStruct,它包含一个MyInterface类型的成员变量interface和一个int类型的成员变量data。最后通过实现接口函数do_something_impl并将它赋值给MyStruct的interface.do_something成员,实现了接口的调用。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)