为什么我们不能初始化结构内部成员? [英] Why can't we initialize members inside a structure?
本文介绍了为什么我们不能初始化结构内部成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我们不能初始化成员的结构里面?
例如:
的struct {
INT I = 10;
};
解决方案
如果您要初始化的非静态在结构
成员<强>声明
在C ++(不是C),结构
几乎是同义类和可以在构造函数初始化成员。
的struct {
INT I; S():我(10)
{
}
};
如果你想初始化的实例
在C或C ++:
的struct {
INT I;
};...的struct s_instance = {10};
C99也有一个被称为指定初始化功能:
的struct {
INT I;
};...的struct s_instance = {
.I = 10,
};
还有一个GNU C扩展,它是非常相似的C99指定的初始值,但最好使用一些更便携的:
的struct s_instance = {
I:10,
};
Why can't we initialize members inside a structure ?
example:
struct s {
int i = 10;
};
解决方案
If you want to initialize non-static members in struct
declaration:
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)
{
}
};
If you want to initialize an instance:
In C or C++:
struct s {
int i;
};
...
struct s s_instance = { 10 };
C99 also has a feature called designated initializers:
struct s {
int i;
};
...
struct s s_instance = {
.i = 10,
};
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屋!
查看全文