C中的默认构造函数 [英] Default constructor in C

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

问题描述

有没有办法为使用结构定义的 C 用户类型拥有某种默认构造函数(如 C++ 构造函数)?

Is there a way to have some kind of default constructor (like a C++ one) for C user types defined with a structure?

我已经有一个像快速初始化程序一样工作的宏(就像 pthread_mutex 的那个),但我想知道你是否可以有任何(或所有)结构的字段填充在声明中.

I already have a macro which works like a fast initializer (like the one for pthread_mutex) but I wanted to know if you can by any chance have some (or all) fields of a struct filled at declaration.

例如,以 pthread_mutex 为例,我希望

For instance, with the pthread_mutex example, I would like

pthread_mutex_t my_mutex;

具有与

pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;

推荐答案

您可以创建带有指向结构的指针的初始化函数.这是常见的做法.

You can create initializer functions that take a pointer to a structure. This was common practice.

还有创建结构并对其进行初始化的函数(如工厂) - 因此在客户端"代码中永远不会有结构未初始化"的情况.当然 - 假设人们遵循约定并使用构造函数"/工厂...

Also functions that create a struct and initialize it (like a factory) - so there is never a time where the struct is "uninitialized" in the "client" code. Of course - that assumes people follow the convention and use the "constructor"/factory...

可怕的伪代码,没有对 malloc 或 free 进行错误检查

horrible pseudo code with NO error checking on malloc or free

somestruct* somestruct_factory(/* per haps some initializer agrs? */)
{
  malloc some stuff
  fill in some stuff
  return pointer to malloced stuff
}


void somestruct_destructor(somestruct*)
{
  do cleanup stuff and also free pointer
  free(somestruct);
}

可能有人会过来解释一些早期的 C++ 预处理器/编译器是如何在 C 中完成这一切的.

Someone will probably come along and explain how some early C++ preprocessors/compilers worked to do this all in C.

这篇关于C中的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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