2010-01-02 39 views
1

可能重複:
Member initialization of a data structure’s membersC++構造函數的初始化列表的語法與數據成員結構?

編輯: 我輸入標題在了最後,它給了我的相關問題lsit,因爲它通常不會。在這個列表的底部是完全相同的問題。 (使用完全相同的代碼;))。 Member initialization of a data structure's members

AraK完全回答,真的。看來我需要投票才能完成我自己的問題?

嗨,

我有一個類,看起來像這樣:

class Button 
{ 
    private: 
     SDL_Rect box; 
    public: 
     Button(int x, int y, int w, int h); 
} 

如果盒子是從SDL these球員之一。與-WeffC++ GCC運行,只是becasue我想知道的警告會是什麼樣的,抱怨的初始化器列表,

file.cpp||In constructor 'Button::Button(int, int, int, int)':| 
file.cpp|168|error: 'Button::box' should be initialized in the member initialization list| 

我想安撫它。我無法弄清楚愚蠢的語法。我試過

Button::Button(int x, int y, int w, int h) : 
    box(0,0,0,0) 

但只是導致

file.cpp||In constructor 'Button::Button(int, int, int, int)':| 
file.cpp|171|error: expected identifier before '{' token| 
file.cpp|171|error: member initializer expression list treated as compound expression| 
file.cpp|171|error: left-hand operand of comma has no effect| 
file.cpp|171|error: right-hand operand of comma has no effect| 
file.cpp|171|error: right-hand operand of comma has no effect| 
file.cpp|171|error: no matching function for call to 'SDL_Rect::SDL_Rect(int)'| 
c:\programming\mingw-4.4.0\bin\..\lib\gcc\mingw32\4.4.0\..\..\..\..\include\SDL\SDL_video.h|50|note: candidates are: SDL_Rect::SDL_Rect(const SDL_Rect&)| 
c:\programming\mingw-4.4.0\bin\..\lib\gcc\mingw32\4.4.0\..\..\..\..\include\SDL\SDL_video.h|50|note:     SDL_Rect::SDL_Rect()| 

我試圖box = blahbox.x = blahbox.x(blah),但他們失敗了。

我也試過box({0,0,0,0}),並且box{0,0,0,0}

file.cpp|169|error: extended initializer lists only available with -std=c++0x or -std=gnu++0x| 
file.cpp|171|error: expected identifier before '{' token| 

我真的不希望被反編譯的C++ 0x,真的。特別是因爲我想這是跨平臺的,我不認爲很多東西都支持C++ 0x。

最後,我設法逃脫:

Button::Button(int x, int y, int w, int h) : 
    box() 
{ 
    box.x = x; 
    box.y = y; 
    box.w = w; 
    box.h = h; 
} 

這似乎完全沒有意義的我。這是做到這一點的「正確」方式嗎?這不就像沒有初始化列表一樣嗎?

回答

2

我看你找到你的解決方案,但請注意,您也可以逃脫寫一個類包裝器SDL_rect,甚至是一個全球性的功能SDL_rect createRect(int x, int y, int w, int h)

+0

好主意。我會在將來記住這一點。 – Pod 2010-01-02 21:47:19