成员初始化一个数据结构的成员 [英] Member initialization of a data structure's members
问题描述
我遇到一个尴尬的问题,有一个容易解决,但不是我喜欢做的。在我的类的构造函数中,我初始化数据成员的数据成员。下面是一些代码:
class Button {
但是,我得到一个编译器错误说:
private:
//按钮的属性
SDL_Rect box;
//将显示的按钮精灵表的部分
SDL_Rect * clip;
public:
//初始化变量
显式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 |
有这样的初始化成员的问题,我需要切换到构造函数体中的赋值。
解决方案只能在
初始化列表
中调用成员变量构造函数。因此,如果SDL_Rect
没有<$ c接受x,y,w,h
的$ c>构造函数,必须在构造函数的主体中执行。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?
解决方案You can only call your member variables constructor in the
initialization list
. So, ifSDL_Rect
doesn't have aconstructor
that acceptsx, y, w, h
, you have to do it in the body of the constructor.这篇关于成员初始化一个数据结构的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!