方便的C ++结构初始化 [英] Convenient C++ struct initialisation
问题描述
我试图找到一种方便的方式来初始化'pod'C ++结构。现在,考虑以下结构:
struct FooBar {
int foo;
float bar;
};
//只是为了使所有示例在C和C ++中工作:
typedef struct FooBar FooBar;
如果我想在C(!)中方便地初始化它, >
/ * A * / FooBar fb = {.foo = 12,.bar = 3.4} //非法C ++,合法C
注意,我想明确避免下面的符号,将来如果我在结构中更改任何,我就会打破我的脖子:
/ * B * / FooBar fb = {12,3.4}; //法律C ++,法律C,坏样式?
要在C ++中实现与在中相同(或至少类似) / * A * /
例如,我将实现一个愚蠢的构造函数:
FooBar :: FooBar(int foo,float bar):foo(foo),bar(bar){}
// - >
/ * C * / FooBar fb(12,3.4);
这对沸水有好处,但不适合懒人(懒惰是好事, ?)。此外,它与 / * B * /
示例差不多,因为它没有明确说明哪个值到哪个成员。
所以,我的问题基本上是如何在C ++中实现类似 / * A * /
或更好的东西?
或者,我可以解释为什么我不应该这样做(即为什么我的心理范例是坏的)。
编辑 >。
由于样式A
不要 style B
那么如何使用 style BX
:
FooBar fb = {/*.foo=*/ 12,/*.bar=*/ 3.4}; // :)
至少在某种程度上有帮助。
I'm trying to find a convenient way to initialise 'pod' C++ structs. Now, consider the following struct:
struct FooBar {
int foo;
float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;
If I want to conveniently initialise this in C (!), I could simply write:
/* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C
Note that I want to explicitly avoid the following notation, because it strikes me as being made to break my neck if I change anything in the struct in the future:
/* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style?
To achieve the same (or at least similar) in C++ as in the /* A */
example, I would have to implement an idiotic constructor:
FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {}
// ->
/* C */ FooBar fb(12, 3.4);
Which is good for boiling water, but not suitable for lazy people (laziness is a good thing, right?). Also, it is pretty much as bad as the /* B */
example, as it does not explicitly state which value goes to which member.
So, my question is basically how I can achieve something similar to /* A */
or better in C++?
Alternatively, I would be okay with an explanation why I should not want to do this (i.e. why my mental paradigm is bad).
EDIT
By convenient, I mean also maintainable and non-redundant.
Since style A
is not allowed in C++ and you don't want style B
then how about using style BX
:
FooBar fb = { /*.foo=*/ 12, /*.bar=*/ 3.4 }; // :)
At least help at some extent.
这篇关于方便的C ++结构初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!