c - 在两个不同的结构之间转换
问题描述
我知道 C 编程可以实现 OOP 概念,我看到一个小代码可以做到这一点,如下所示。但是 main 函数中的实现让我感到困惑:
Car c;
vehicleStart((Vehicle*) &c);
为什么 struct Car c 可以直接传递给 vehicleStart 参数,虽然它已经进行了类型转换。我认为他们在结构中有不同的类型,
Vehicle base;
Object base;
所以这个操作让我感到困惑。
#include <stdio.h>
typedef struct Object Object; //!< Object type
typedef struct Vehicle Vehicle; //!< Vehicle type
typedef struct Car Car; //!< Car type
typedef struct Truck Truck; //!< Truck type
/*!
* Base object class.
*/
struct Object {
int ref; //!< \private Reference count.
};
static Object * objRef(Object *obj);
static Object * objUnref(Object *obj);
struct Vehicle {
Object base; //!< \protected Base class.
};
void vehicleStart(Vehicle *obj);
void vehicleStop(Vehicle *obj);
struct Car {
Vehicle base; //!< \protected Base class.
};
struct Truck {
Vehicle base; //!< \protected Base class.
};
/* implementation */
void vehicleStart(Vehicle *obj)
{
if (obj) printf("%x derived from %x\n", obj, obj->base);
}
int main(void)
{
Car c;
vehicleStart((Vehicle*) &c);
}
解决方案
推荐阅读
- react-spring - 如何在单个组件上附加多个反应弹簧?
- c - c语言中的面试题reg二进制位操作
- docker - 如何从 docker-compose 或 docker run 写入现有的填充卷
- javascript - 根据日期从数据库中获取唯一值,当用户单击日期时,然后展开数据库中可用的详细信息
- javascript - 如何通过同一行的另一列的一个文本框中的输入获取值
- flutter - 如何在 vscode 中禁用“运行|调试”行?
- javascript - 使用 fetch API 和 NodeJS(express)
- python - 在pygame中出现游戏结束屏幕后重新启动蛇游戏
- c++ - 需要一个标识符
- python - 使用 pip 安装 wheel 文件后,找不到模块错误