成员初始化一个数据结构的成员 [英] Member initialization of a data structure's members

查看:89
本文介绍了成员初始化一个数据结构的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个尴尬的问题,有一个容易解决,但不是我喜欢做的。在我的类的构造函数中,我初始化数据成员的数据成员。下面是一些代码:

  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, 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.

这篇关于成员初始化一个数据结构的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆