简体   繁体   English

(为什么不)在定义时初始化 struct val

[英](Why not) initialize struct val at definition

I know this kind of initialisation is discouraged but I can't remember why, while it's working, so does anyone knows why this should be avoided :我知道不鼓励这种初始化,但我不记得为什么,当它工作时,有人知道为什么应该避免这种情况:

typedef struct struct_test {
    int a = 1;
    int b = 2;
    int c = 3;
} t_test;

thanks谢谢

It's illegal in C.在 C 中是非法的。

In C++ it's not discouraged.在 C++ 中,它并不气馁。 Unlike initializing in the constructor, it doesn't require you to list all fields the second time (see DRY ), making it harder to forget to initialize fields.与在构造函数中初始化不同,它不需要您第二次列出所有字段(参见DRY ),从而更难忘记初始化字段。

While initializing a struct val at definition is not allowed in C It's perfectly correct in C++虽然在 C 中不允许在定义时初始化 struct val在 C++ 中是完全正确的

the confusion can arise when compiling a .cpp with gcc that allow this syntax in this case.在这种情况下,使用允许这种语法的 gcc 编译 .cpp 时可能会出现混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM