首页 > 解决方案 > 在两个不同的结构之间转换

问题描述

我知道 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);
}

标签: coop

解决方案


推荐阅读