在myClass的構造函數中,在下面的代碼中,我使用ms({4,5})
初始化ms
。在類構造函數中初始化自定義結構對象的正確方法
#include <iostream>
class myClass {
private:
struct myStruct {
int val1;
int val2;
};
public:
myStruct ms;
myClass() : ms({4,5}){} // This is where I initialize ms!
};
int main(){
myClass mc;
std::cout << mc.ms.val1 << " " << mc.ms.val2 << std::endl;
return 0;
};
但是,我們在成員初始化列表,因此參數ms
是參數的MS的構造。這裏基本上是會發生什麼, ,是我們使用的所謂「列表初始化」到 創建一個未命名(匿名)myStruct
對象:「{4,5}」,然後我們 通該對象的ms
構造。因此,在原則上,在創建 匿名中間對象,複製到初始化ms
, ,然後銷燬(雖然我敢肯定,編譯器知道 更好,直接初始化ms
;但仍有 語義差別)。有人告訴我,而不是ms({4,5})
我可以簡單地做
ms(4,5)
,並避免中間對象。然而,當我這樣做,我得到下面的輸出:
g++ -g -std=c++11 -Wall temp.cpp -o temp
temp.cpp: In constructor ‘myClass::myClass()’:
temp.cpp:12:21: error: no matching function for call to ‘myClass::myStruct::myStruct(int, int)’
myClass() : ms(4,5){}
^
temp.cpp:5:10: note: candidate: myClass::myStruct::myStruct()
struct myStruct {
^
temp.cpp:5:10: note: candidate expects 0 arguments, 2 provided
temp.cpp:5:10: note: candidate: constexpr myClass::myStruct::myStruct(const myClass::myStruct&)
temp.cpp:5:10: note: candidate expects 1 argument, 2 provided
temp.cpp:5:10: note: candidate: constexpr myClass::myStruct::myStruct(myClass::myStruct&&)
temp.cpp:5:10: note: candidate expects 1 argument, 2 provided
makefile:15: recipe for target 'temp' failed
make: *** [temp] Error 1
所以,要清楚,我想知道最好的做法是什麼,在一個類的構造函數初始化一個struct對象的條款。所有的幫助非常感謝!
http://stackoverflow.com/questions/4203010/how-to-initialize-member-struct-in-initializer-list-of-c-class – dmi
謝謝@dmi。這給了我一些見解,但它似乎沒有妥善回答我的問題。 – JCKaz