铸造1结构指针其他 - ç [英] Casting one struct pointer to other - C

查看:174
本文介绍了铸造1结构指针其他 - ç的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下code。

enum type {CONS, ATOM, FUNC, LAMBDA};

typedef struct{
  enum type type;
} object;

typedef struct {
  enum type type;
  object *car;
  object *cdr;
} cons_object;

object *cons (object *first, object *second) {
  cons_object *ptr = (cons_object *) malloc (sizeof (cons_object));
  ptr->type = CONS;
  ptr->car = first;
  ptr->cdr = second;
  return (object *) ptr;
}

劣势函数,变量 PTR 的类型为 cons_object * 。但在返回值被转换成键入对象* 的。

In the cons function, variable ptr is of type cons_object*. But in the return value it is converted to type of object*.


  1. 我想知道这是怎么可能的,因为 cons_object 对象是不同的结构。

  2. 有没有做这样的东西的任何问题?

  1. I am wondering how this is possible because cons_object and object are different structs.
  2. Are there any issues in doing stuff like this?

有什么想法!

推荐答案

这是罚款,是在C.执行面向对象一个相当常见的技术,因为的结构 s是用C定义良好的,只要两个对象共享相同的布局,那么你可以放心地在它们之间投三分球。也就是说,偏移量键入成员是在对象相同结构,因为它是在 cons_object 结构。

This is fine and is a fairly common technique for implementing "object-orientation" in C. Because the memory layout of structs is well-defined in C, as long as the two object share the same layout then you can safely cast pointers between them. That is, the offset of the type member is the same in the object struct as it is in the cons_object struct.

在这种情况下,键入成员告诉API的对象是否是 cons_object foo_object 或一些其他类型的对象,所以你可能会看到这样的事情:

In this case, the type member tells the API whether the object is a cons_object or foo_object or some other kind of object, so you might be see something like this:

void traverse(object *obj)
{
    if (obj->type == CONS) {
        cons_object *cons = (cons_object *)obj;
        traverse(cons->car);
        traverse(cons->cdr);
    } else if (obj->type == FOO) {
        foo_object *foo = (foo_object *)obj;
        traverse_foo(foo);
    } else ... etc
}

更常见的是,我似乎在哪里父类定义为子类的第一个成员,像这样实现的:

More commonly, I've seem implementations where the "parent" class is defined as the first member of the "child" class, like so:

typedef struct {
    enum type type;
} object;

typedef struct {
    object parent;

    object *car;
    object *cdr;
} cons_object;

这工作在大致相同的方式,除非你有一个强大的gaurantee孩子类的内存布局将是一样的父母。也就是说,如果一个成员添加到基地对象,它会自动被孩子们拿起你将不必手动确保所有的结构是同步的。

This works in largely the same way, except you've got a strong gaurantee that the memory layout of the child "classes" will be the same as the parents. That is, if you add a member to the 'base' object, it'll automatically be picked up by the children and you won't have to manually make sure all of the structures are in sync.

这篇关于铸造1结构指针其他 - ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆