C语言 C 中结构的构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3774193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:30:12  来源:igfitidea点击:

Constructor for structs in C

cstructinitialization

提问by Aillyn

Given:

鉴于:

struct objStruct {
    int id;
    int value;
};

typedef struct objStruct Object;

Is there a shortcut to allocate and initialize the object, something like a C++ constructor?
It could even be a preprocessor macro. Whatever makes the code shorter and more readable than this:

是否有分配和初始化对象的快捷方式,例如 C++ 构造函数?
它甚至可以是一个预处理器宏。无论什么使代码更短、更易读:

Object *newObj = malloc(sizeof(Object));
// successful allocation test snipped
newObj->id = id++;
newObj->value = myValue;

回答by JaredPar

In C I typically create a function in the style of a constructor which does this. For example (error checking omitted for brevity)

在 CI 中,通常会以构造函数的风格创建一个函数来执行此操作。例如(为简洁起见省略了错误检查)

Object* Object_new(int id, int value) { 
  Object* p = malloc(sizeof(Object));
  p->id = id;
  p->value = value;
  return p;
}

...
Object* p1 = Object_new(id++, myValue);

回答by Jonathan Leffler

In C99 and beyond, you can use a compound literal, which looks like a cast followed by an initializer in braces:

在 C99 及更高版本中,您可以使用复合字面量,它看起来像一个强制转换,后跟一个大括号中的初始化程序:

int init_value = ...;
int init_id    = ...;
Object newObj1 = (Object){ .value = init_value, .id = init_id };
Object newObj2 = (Object){ .id = init_id, .value = init_value };

The latter two lines achieve the same effect - the order of the fields is not critical. That is using 'designated initializers', another C99 feature. You can create a compound literal without using designated initializers.

后两行实现了相同的效果 - 字段的顺序并不重要。那就是使用“指定的初始值设定项”,这是另一个 C99 特性。您可以在不使用指定初始值设定项的情况下创建复合文字。

回答by grekhss

In C it is possible to declare an inline function with the same name as structure:

在 C 中,可以声明一个与结构同名的内联函数:

struct my
{
    int a;
};

inline struct my* my(int* a)
{
    return (struct my*)(a);
}

//somewhere in code
int num = 123;
struct my *sample = my(&num);
//somewhere in code

It looks pretty similar to C++ ctors.

它看起来与 C++ ctors 非常相似。

回答by nategoose

struct thingy {
   char * label;
   int x;
};

#define declare_thingy( name, label, val) struct thingy name = { label, val }

struct thingy * new_thingy(const char * label, int val) {
     struct thingy * p = malloc(sizeof(struct thingy));
     if (p) {
          p->label = label;
          p->val = val;
     }
     return p;
}

回答by Jens Gustedt

You really have to distinguish initialization of staticor autovariables and dynamic allocation on the head. For the first, do named initializers, for the second a well specified init function.

您确实必须在头上区分staticauto变量的初始化和动态分配。对于第一个,执行命名初始化程序,对于第二个,执行一个明确指定的 init 函数。

All that can be nicely packed into macrosdo give you an easy static/autointialization and something similar to newin C++.

所有可以很好地 打包到宏中的东西确实可以为您提供简单的static/auto初始化和类似于newC++ 的东西。

回答by Tarantula

If you are looking for an object oriented "emulation" over C, I strongly recommend the GObject Type System [1], it's mature and largely used by GTK for instance.

如果您正在寻找一种基于 C 的面向对象的“仿真”,我强烈推荐 GObject 类型系统 [1],例如,它已经成熟并被 GTK 大量使用。

GLib [2] has also a nice slice allocator for small objects, currently used by GNOME.

GLib [2] 也有一个很好的小对象切片分配器,目前由 GNOME 使用。

[1] GObject Reference Manual

[1] GObject 参考手册

[2] GLib Memory Slices

[2] GLib 内存片