non-aggregates(非聚合)对象不能使用初始化列表
生活随笔
收集整理的這篇文章主要介紹了
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}處會出現錯誤,錯誤類型為:
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; }轉載于:https://blog.51cto.com/whatever957/1605225
總結
以上是生活随笔為你收集整理的non-aggregates(非聚合)对象不能使用初始化列表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python使用pyodbc,freet
- 下一篇: 医学教育网批量资源下载程序之——完成