Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中实现结构构造函数时出错_C_Struct_Constructor - Fatal编程技术网

在C中实现结构构造函数时出错

在C中实现结构构造函数时出错,c,struct,constructor,C,Struct,Constructor,我在试图用C语言实现一个带有结构的构造函数时遇到了这个错误。我不明白,因为我在网上读到的内容 #170 a function type is not allowed here 这是结构定义 typedef struct ConnectionTestResults_t { ConnectionError_t detectedErrors; bool isTempShorted; bool isRespShorted; in

我在试图用C语言实现一个带有结构的构造函数时遇到了这个错误。我不明白,因为我在网上读到的内容

#170 a function type is not allowed here    
这是结构定义

typedef struct ConnectionTestResults_t {

        ConnectionError_t detectedErrors;
        bool isTempShorted;
        bool isRespShorted;
        int8_t conn1ShortedPins[2];
        int8_t conn2ShortedPins[2];
        int8_t spo21ShortedPins[2];
        int8_t spo22ShortedPins[2];
        int8_t usbShortedPins[2];
        int8_t conn1OpenPins[2];
        int8_t conn2OpenPins[2];
        int8_t spo21OpenPins[2];
        int8_t spo22OpenPins[2];
        int8_t usbOpenPins[2];
        ConnectionTestResults_t() {
            conn1ShortedPins = {-1,-1};
        }

} ConnectionTestResults_t;
谢谢

>构造函数是C++(ETC)的东西,通常会将它们与面向对象的编程关联,而C不是./P> 如果你想,你可以实现一个初始化功能,类似于

function void someFunction(ConnectionTestResults_t * instance) {
   ...
}

function void initConnectionTestResult(ConnectionTestResults_t * ctr) {
  ctr->myFunc = &someFunction;
  ctr->initialisableValue = INITIAL_VALUE;
}
(为语法道歉,我已经有一段时间没有做过C编程了)

如果你想实现OO方法之类的东西,最接近的方法是

ConnectionTestResults_t thing;
initConnectionTestResult(&thing);
thing.myFunc(&thing);
包括一个类型字段,打开它是实现它的另一种方式

if (thing->isAFoo) {
  fooIt(&thing);
} else {
  barIt(&thing);
}

但是,如果这是实现你目标的正确方法。

构造函数是C++特性。你不能在C语言中在C.中拥有成员函数,而不是独立的非成员全局函数,它可能创建并初始化结构。它要么使用了错误的语言,要么是不正确的。我认为将构造函数设为返回函数是很干净的,因此没有通过引用传递,而是没有参数和thing=init()。你认为使用你的方法、少用内存或其他什么方法是有利的吗?ThanksIt取决于要管理内存的实体。如果您执行
thing=init()
操作,则thing必须位于堆上(即,您将
malloc
放入
init
),否则它将位于堆栈上,并且(可能)在init返回时被覆盖!当您需要确保设计被取消分配时,这会约束您的设计-哪种代码单元具有这种可重复性?如果改为按ref传递,则可以根据需要将对象放在堆栈或堆上。