最近在写代码定义结构体时遇到初始化的问题,针对c++11发现可以用下面的方法的初始化:
1. 定义结构体的时候直接赋值
在定义结构体数组时直接赋值初始化
typedef struct SScrollViewItem {
NcString* iconPath = NULL;
uint32 itemMsgId = 0;
BOOL isSelected = FALSE;
BOOL Disable = FALSE;
} SScrollViewItem;
2. 构造函数初始化
c++结构体可以有构造函数、成员函数等,对于上面那种也可以在构造函数中用 memset 来初始化:
typedef struct SScrollViewItem {
NcString* iconPath = NULL;
uint32 itemMsgId = 0;
BOOL isSelected = FALSE;
BOOL Disable = FALSE;
SScrollViewItem() {
memset(this, 0, sizeof(*this));
}
} SScrollViewItem;
但是这种方法对有变量、数组、vector容器等嵌套的复杂结构体,类似下面这种就容易出错:
typedef struct tagDataInfo {
long offs; // 索引
char name[20]; // 姓名
std::list<int> ord_list; // 定单索引列表
std::map<std::string, std::string> str_map; // 编号对应管理
} DataInfo;
正确初始化的写法如下:
typedef struct tagDataInfo {
long offs; // 索引
char name[20]; // 姓名
std::list<int> ord_list; // 定单索引列表
std::map<std::string, std::string> str_map; // 编号对应管理
tagDataInfo() : offs(0) {
memset(name, '0', sizeof(char) * 20);
ord_list.clear();
str_map.clear();
};
} DataInfo;
具体原因详见 https://blog.youkuaiyun.com/changqing5818/article/details/78523299