例子:
#include "stdafx.h" #include <iostream> using std::cout; using std::endl; struct Test { int a; int b; Test() { memset(this, 0, sizeof(Test)); } }; int _tmain(int argc, _TCHAR* argv[]) { Test test = { 0 }; cout << test.a << " " << test.b << endl; system("pause"); return 0; }
按照如上程序编写,在Test test = {0}处会出现错误,错误类型为:
non-aggregates cannot be initialized with initializer list(
“初始化”: 无法从“initializer-list”转换为“Test”
1> 无构造函数可以接受源类型,或构造函数重载决策不明确
)
错误原因分析:
对于non-aggregates(非聚合对象),不能使用初始化列表。只有聚合对象才可以这样使用。
而聚合对象定义为:
1. 数组
2. 不包含 ( 构造函数、private和protect、基类、虚函数 )的类、结构体和联合体
也就是说,不满足聚合对象定义而使用初始化列表都会产生这样的错误。使用时需注意。
也即凡是结构体内拥有构造函数,类或Union联合体,都属于非聚合对象,不能使用初始化列表。
(注:CString等也属于类,若结构体内有CString类型成员变量,则不能使用初始化列表进行初始化。)
解决方案:
#include "stdafx.h" #include <iostream> using std::cout; using std::endl; struct Test { int a; int b; Test() { memset(this, 0, sizeof(Test)); } }; int _tmain(int argc, _TCHAR* argv[]) { Test test; test.a = 1; test.b = 2; cout << test.a << " " << test.b << endl; system("pause"); return 0; }