C/C++结构体初始化

来源:互联网 发布:mac复制u盘文件到电脑 编辑:程序博客网 时间:2024/05/19 19:58

对于像简单的结构体数据,如:

struct A{int a;int b;};A temp[4] = { 0 };

这样直接进行初始化就可以了。但是如果在结构体中又包含一个类时,再这样进行初始化就会出现严重问题,再第二次使用他时不能成功初始化,直接会导致程序崩溃。如:

struct A{int a;int b;string c;};A temp[4] = { 0 }; //error

而应该是这样的:

struct A{int a;int b;string c;};/**temp:结构体指针*len:结构体数组长度*/int InitAStruct(A *temp,int len) {for (int i = 0;i < len;i++) {temp->a = 0;temp->b = 0;temp->c = "";++temp;}return 0;}//A temp[4] = { 0 }; //errorA temp[4];InitAStruct(temp,4);//right

因为其中包含了类(string)的存在,所以不能用普通方式进行初始化

0 0
原创粉丝点击