Error when initializing a struct with a brace-enclosed initializer list

眉间皱痕 提交于 2021-01-27 02:38:24

问题


struct CLICKABLE
{
    int x;
    int y;
    BITMAP* alt;
    BITMAP* bitmap;

    CLICKABLE()
    {
        alt=0;
    }
};

CLICKABLE input={1,2,0,0};

This code gives me the following error:

Could not convert from brace-enclosed initializer list

Could someone explain me why the compiler is giving me this error, and how I can fix it? I'm still learning the language.


回答1:


Your class has a constructor, so it isn't an aggregate, meaning you cannot use aggregate initialization. You can add a constructor taking the right number and type of parameters:

struct CLICKABLE
{
  int x;
  int y;
  BITMAP* alt;
  BITMAP* bitmap;

  CLICKABLE(int x, int y, BITMAP* alt, BITMAP* bitmap) 
  : x(x), y(y), alt(alt), bitmap(bitmap) { ... }

  CLICKABLE() : x(), y(), alt(), bitmap() {}

};

Alternatively, you can remove the user declared constructors, and use aggregate initialization:

CLICKABLE a = {};         // all members are zero-initialized
CLICKABLE b = {1,2,0,0};


来源:https://stackoverflow.com/questions/24751567/error-when-initializing-a-struct-with-a-brace-enclosed-initializer-list

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