赞
踩
结构体初始化我们经常会用到,使用未初始化的结构体,结果是不可预估的
下面介绍几种常用的结构体初始化方式:
typedef struct stTemp { int nName; int nType; char arrayTemp[50]; stTemp():nName(-1),nType(-1) //构造函数初始化列表 //也可用 struct stTemp():nName(-1),nType(-1) vs2015可用 //但struct关键字部分编译器不识别 { memset(arrayTemp,0,sizeof(arrayTemp)); } }STT; //或 typedef struct stTemp { int nName; int nType; char arrayTemp[50]; stTemp() { nName = -1; nType = -1; memset(arrayTemp,0,sizeof(arrayTemp)); } }STT;
typedef struct stTemp
{
int nName;
int nType;
char arrayTemp[50];
stTemp()
{
memset(this,0,sizeof(stTemp));
}
}STT;
typedef struct stTemp
{
int nName;
int nType;
char arrayTemp[50];
}STT;
STT stMy = {0};
很多时候,结构体指针就是结构体内第一个元素的指针,所以有时候可以这样初始化:
typedef struct stBase { int id; int width; int height; const char *name; }STBASE; typedef struct stTemp { STBASE a; STBASE b; STBASE c; const char name[3][16] = {{"中国"},{"美国"},{"英国"}}; struct stTemp () { STBASE *val = 0; val = (STBASE*)this; for(int i=0; i<3; ++i) { val->id = 0; val->width = -1; val->height = -1; val->name = name[i]; ++val; } } }STT;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。