首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c中构造体的初始化的疑问

2013-01-09 
c中结构体的初始化的疑问struct Test{int tint s} 结构也可以这样初始化,struct Test q {1, 2}但是

c中结构体的初始化的疑问
struct Test{    int t;    int s;}; 
结构也可以这样初始化, 
 struct Test q = {1, 2};
但是肯定不能这样复制。只是c中这样初始化的原理是什么。感觉比较奇怪,之前也没有这样初始化过。
[解决办法]
这是一种比较方便的初始化方法,就是让你可以在定义的时候进行初始化。
至于原理,不知道你要什么原理,只是方便的原理而已。
[解决办法]
Aggregate(聚合)的初始化式

ISO C++ 2003 标准 $8.5.1/1
An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).


ISO C++ 2003 标准 $8.5.1/2
When an aggregate is initialized the initializer can contain an initializer-clause consisting of a brace-enclosed, comma-separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order. If the aggregate contains subaggregates, this rule applies recursively to the members of the subaggregate. [[Example:

struct A {
int x;
struct B {
int i;
int j;
} b;
} a = { 1, { 2, 3 } };

initializes a.x with 1, a.b.i with 2, a.b.j with 3. ]
[解决办法]
个人觉得可以结合c++ 类的初始化来理解。
结构体的默认访问属性为 public,即可以直接访问其中成员变量,所以可以采用这种初始化时直接指定成员的方式。
结构体的初始化有点类似数组的初始化,只不过数组中存的是同一类型的值罢了。
即在定义结构体时,分配结构体内存空间,然后根据声明结构体成员的顺序,然后把初始化式中的数据给放进去就行了。

热点排行