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

查看:35
本文介绍了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).

我希望我已经足够精确了.

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;
    //...
  }
  //...
}

第二个选项,如果你想避免开关/大小写,并且能够在之后添加更多的结构类型,而不演变 foo,你可以确保你的所有结构 开始 以必要的数据,总是以相同的顺序,使用相同的类型.这样您就可以从 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部分放在struct 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天全站免登陆