加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

non-aggregates(非聚合)对象不能使用初始化列表

发布时间:2020-12-14 05:19:26 所属栏目:百科 来源:网络整理
导读:例子: #include?"stdafx.h"#include?iostreamusing?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

例子:

#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,?_TCHAR*?argv[])
{
	Test?test;
	test.a?=?1;
	test.b?=?2;
	cout?<<?test.a?<<?"?"?<<?test.b?<<?endl;

	system("pause");
	return?0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读