为什么我们不能在结构中初始化成员? [英] Why can't we initialize members inside a structure?
本文介绍了为什么我们不能在结构中初始化成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我们不能在结构中初始化成员?
Why can't we initialize members inside a structure ?
示例:
struct s {
int i = 10;
};
推荐答案
如果要在struct
声明中初始化非静态成员:
If you want to initialize non-static members in struct
declaration:
在 C++(不是 C)中,structs
几乎是类的同义词,并且可以在构造函数中初始化成员.
In C++ (not C), structs
are almost synonymous to classes and can have members initialized in the constructor.
struct s {
int i;
s(): i(10)
{
}
};
如果你想初始化一个实例:
在 C 或 C++ 中:
In C or C++:
struct s {
int i;
};
...
struct s s_instance = { 10 };
C99 还有一个称为指定初始化器的特性:
C99 also has a feature called designated initializers:
struct s {
int i;
};
...
struct s s_instance = {
.i = 10,
};
还有一个 GNU C 扩展,它与 C99 指定初始化器非常相似,但最好使用更便携的东西:
There is also a GNU C extension which is very similar to C99 designated initializers, but it's better to use something more portable:
struct s s_instance = {
i: 10,
};
这篇关于为什么我们不能在结构中初始化成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文