Member initialization of a data structure's members

安稳与你 提交于 2019-12-12 09:09:04

问题


I just ran into an awkward issue that has an easy fix, but not one that I enjoy doing. In my class's constructor I'm initializing the data members of a data member. Here is some code:

class Button {
private:
    // The attributes of the button
    SDL_Rect box;

    // The part of the button sprite sheet that will be shown
    SDL_Rect* clip;

public:
    // Initialize the variables
    explicit Button(const int x, const int y, const int w, const int h)
        : box.x(x), box.y(y), box.w(w), box.h(h), clip(&clips[CLIP_MOUSEOUT]) {}

However, I get a compiler error saying:

C:\Users\Alex\C++\LearnSDL\mouseEvents.cpp|56|error: expected `(' before '.' token|

and

C:\Users\Alex\C++\LearnSDL\mouseEvents.cpp|56|error: expected `{' before '.' token|

Is there a problem with initializing member in this way and will I need to switch to assignment in the body of the constructor?


回答1:


You can only call your member variables constructor in the initialization list. So, if SDL_Rect doesn't have a constructor that accepts x, y, w, h, you have to do it in the body of the constructor.




回答2:


The following is useful when St is not in your control and thus you cannot write a proper constructor.

struct St
{
    int x;
    int y;
};

const St init = {1, 2};

class C
{
public:
    C() : s(init) {}

    St s;
};


来源:https://stackoverflow.com/questions/1480430/member-initialization-of-a-data-structures-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!