开发者

c++ Syntax of a constructor's initialization list with a data member struct? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Member initialization of a data structure’s members

EDIT: I typed the title in last, and it gave me a lsit of relat开发者_开发知识库ed problems, as it usually does. At the bottom of this list was the exact same problem. (Using the exact same code ;)). Member initialization of a data structure's members

AraK answers it fully, really. It appears I need to vote in order to close my own question?

Hi,

I have a class that looks like this:

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

Where box is one of these guys from SDL. Running with GCC with -Weffc++, just becasue I wanted to know what the warnings would be like, complains about the initialiser list,

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

I would like to appease it. I can't figure out the stupid syntax though. I've tried

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

but that just results in

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()|

I tried box = blah or box.x = blah or box.x(blah), but they failed.

I also tried box({0,0,0,0}), and 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|

I don't really want to be compiling against c++0x, really. Especially as I want this to be cross platform, and I don't think many things support c++0x.

In the end I managed to get away with:

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

Which seems entirely pointless to me. Is this the 'correct' way to do this? Isn't this just the same as without the initialiser list?


I see you found your solution, but please note that you could also get away with writing a class wrapper for SDL_rect, or even a global function SDL_rect createRect( int x, int y, int w, int h )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜