C:发送不同的结构,一个函数的参数 [英] C : send different structures for one function argument

查看:147
本文介绍了C:发送不同的结构,一个函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用OpenGL绘制一个圆形功能,我想通过它含有X和Y坐标和半径的结构。问题是这样的同样的功能具有与3个不同的结构都包含的坐标,半径和拉伸功能不使用一些其他的事情一起使用。

I have a function that draws a circle using OpenGL, I would like to pass it a structure containing the x and y coordinates and the radius. The problem is this same function has to be used with 3 different structures all containing the coordinates, radius and some other things that the draw function doesn't use.

有一些办法只能有3种不同的结构(仅一次发送)。

Is there some way to only have one argument for 3 different structures (only one is sent at a time).

我希望我已经够了precise。

I hope I've been enough precise.

PS:功能却是抽象的

PS : the functions have to be "abstract".

推荐答案

是的,你可以使用一个原型是这样的:

Yes you can use a prototype like this:

void foo(char type, void *data);

使用的类型告诉函数使用数据作为结构,你是好。

Use the type to tell the function which struct to use the data as, and you're good.

struct c *prepareStructC(void);
//...
struct c *toto = prepareStructC();
foo('c', toto);
//...
void foo(char type, void *data)
{
  int x, y;
  switch (type)
  {
    case 'c':
      x = ((struct c*)data)->x;
      y = ((struct c*)data)->y;
      break;
    //...
  }
  //...
}

第二种选择,如果你想避免一个开关/箱,并能够在事后添加更多的结构类型,没有演变富,可以确保所有结构的开始必要的数据,总是以相同的顺序,具有相同的类型。这种方式可以使一些像C ++一个接口,并使用类型的抽象形式:

Second option, if you want to avoid a switch/case, and be able to add more struct types afterwards, without evolving foo, you can make sure all your structs begin with the necessary data, always in the same order, with the same type. This way you can make something like an "interface" from C++, and use abstract versions of the type:

struct abstract
{
  int x;
  int y;
  int radius;
}

struct a
{
  struct abstract abs;
  //... other data ...
}
struct b
{
  struct abstract abs;
  //... other data ...
}
struct c
{
  struct abstract abs;
  //... other data ...
}

//Two choices : either you have:
void foo(void *data)
{
  int x,y,r;
  x = ((struct abstract*)data)->x;
  y = ((struct abstract*)data)->y;
  r = ((struct abstract*)data)->radius;
  //...
}

//OR Smarter way:
void foo2(struct abstract *data)
{
  int x,y,r;
  x = data->x;
  y = data->y;
  r = data->radius;
}
//Calling foo2 with:
struct a *sa = prepareStructA();
struct b *sb = prepareStructB();
struct c *sc = prepareStructC();
foo2(sa->abs);
foo2(sb->abs);
foo2(sc->abs);

第二个方法的第二部分可以让你更多的灵活性,在亚型打破的具体信息,使您能够把 ABS 部分的任何位置结构的a / b内/ C,而且是在一个单一的目的,原则,一个结构更好的(一个结构里面有坐标和半径其他的事情并不总是最好的。)

The second part of the second method allows you more flexibility, breaking down specific information in a subtype, enables you to put the abs part anywhere inside the struct a/b/c, and is better in the principle of a single purpose for a struct (Having coordinates and radius and other things inside a struct is not always the best.)

这篇关于C:发送不同的结构,一个函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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