构造函数在C结构 [英] Constructor for structs in C

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

问题描述

假设:

 结构objStruct {
    INT ID;
    int值;
};typedef结构objStruct对象;

有一个快捷方式来分配和初始化对象,有点像C ++的构造函数?结果
它甚至可以是一个preprocessor宏。无论使得code比这更短,更具可读性:

 对象* newObj =的malloc(sizeof的(对象));
//分配成功测试剪断
newObj-> ID = ID ++;
newObj->值= myvalue的;


解决方案

在C I通常创建一个构造函数,做到这一点的风格的功能。例如(检查不再赘述错误)

 对象* Object_new(INT ID,int值){
  对象* P =的malloc(sizeof的(对象));
  P-> ID = ID;
  P->值=价值;
  回磷;
}...
对象* P1 = Object_new(ID ++,myvalue的);

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:

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

解决方案

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

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);

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

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