我工作的公司正在通过初始化函数来初始化所有数据结构,如下所示:
//the structure
typedef struct{
int a,b,c;
} Foo;
//the initialize function
InitializeFoo(Foo* const foo){
foo->a = x; //derived here based on other data
foo->b = y; //derived here based on other data
foo->c = z; //derived here based on other data
}
//initializing the structure
Foo foo;
InitializeFoo(&foo);
我遇到了一些尝试初始化我的结构的问题:
//the structure
typedef struct{
int a,b,c;
} Foo;
//the initialize function
Foo ConstructFoo(int a, int b, int c){
Foo foo;
foo.a = a; //part of parameter input (inputs derived outside of function)
foo.b = b; //part of parameter input (inputs derived outside of function)
foo.c = c; //part of parameter input (inputs derived outside of function)
return foo;
}
//initialize (or construct) the structure
Foo foo = ConstructFoo(x,y,z);
一个人比另一个人有优势吗?
我应该怎么做,我将如何证明它是一种更好的做法?
InitializeFoo()
是构造函数。与C ++构造函数的唯一区别是,this
指针是显式传递的,而不是隐式传递的。InitializeFoo()
和相应的C ++ 的编译代码Foo::Foo()
完全相同。