例子:
#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”
)
错误原因分析:
对于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, _TCHAR* argv[]) { Test test; test.a = 1; test.b = 2; cout << test.a << " " << test.b << endl; system("pause"); return 0; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。