可能重复:
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 = blah
或box.x = blah
或box.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;
}
这似乎完全没有意义的我。这是做到这一点的“正确”方式吗?这不就像没有初始化列表一样吗?
好主意。我会在将来记住这一点。 – Pod 2010-01-02 21:47:19