non-aggregates(非聚合)对象不能使用初始化列表
例子:
#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}處會出現(xiàn)錯誤,錯誤類型為:
non-aggregates cannot be initialized with initializer list(
“初始化”: 無法從“initializer-list”轉(zhuǎn)換為“Test”
1> ? ? ? ? ?無構(gòu)造函數(shù)可以接受源類型,或構(gòu)造函數(shù)重載決策不明確
)
錯誤原因分析:
對于non-aggregates(非聚合對象),不能使用初始化列表。只有聚合對象才可以這樣使用。
而聚合對象定義為:
1. 數(shù)組
2. 不包含 ( 構(gòu)造函數(shù)、private和protect、基類、虛函數(shù) )的類、結(jié)構(gòu)體和聯(lián)合體
也就是說,不滿足聚合對象定義而使用初始化列表都會產(chǎn)生這樣的錯誤。使用時需注意。
也即凡是結(jié)構(gòu)體內(nèi)擁有構(gòu)造函數(shù),類或Union聯(lián)合體,都屬于非聚合對象,不能使用初始化列表。
(注:CString等也屬于類,若結(jié)構(gòu)體內(nèi)有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; }轉(zhuǎn)載于:https://blog.51cto.com/whatever957/1605225
總結(jié)
以上是生活随笔為你收集整理的non-aggregates(非聚合)对象不能使用初始化列表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python使用pyodbc,freet
- 下一篇: 医学教育网批量资源下载程序之——完成