2009-09-26 141 views
2

我刚碰到一个尴尬的问题,有一个简单的修复,但不是我喜欢做的一个。在我的类的构造函数中,我正在初始化数据成员的数据成员。下面是一些代码:成员初始化数据结构的成员

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]) {} 

但是,我得到一个编译错误说:

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

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

有没有以这种方式初始化成员一个问题,我需要切换到构造函数体中的赋值?

回答

5

您只能在initialization list中调用您的成员变量构造函数。因此,如果SDL_Rect没有接受x, y, w, hconstructor,则必须在构造函数的主体中执行此操作。

+6

或者写一个帮助函数,它接受这4个参数并返回一个'SDL_Rect'。然后你可以在初始化列表中调用它。 – jalf 2009-09-26 10:45:58

3

当St不在你的控制范围内时,以下是有用的,因此你不能写出正确的构造函数。

struct St 
{ 
    int x; 
    int y; 
}; 

const St init = {1, 2}; 

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

    St s; 
};