“Y does not name a type” error in C++

末鹿安然 提交于 2019-11-29 03:42:58

You cannot put assignments outside the context of a function in C++. If you're puzzled by the fact that you sometimes saw the = symbol being used outside the context of a function, such as:

int x = 42; // <== THIS IS NOT AN ASSIGNMENT!

int main()
{
    // ...
}

That's because the = symbol can be used for initialization as well. In your example, you are not initializing the data members width and height, you are assigning a value to them.

Ralph Tandetzky

In C++11 you can write

struct Settings {
    int width;
    int height;
} settings = { 800, 600 };

in order to fix your bug. The error appears because you're trying to assign a value outside a function body. You can initialize but not assign global data outside of a function.

EDIT:

Concerning your edit, just write

Settings settings = {{800, 600}, {10, 20, 3}};

I'm not 100% sure, if this works though, because of the inheritance. I would recommend to avoid inheritance in this case and write the Dimensions as member data into your Build_menu structure. Inheritance will sooner or later give you all kinds of trouble, when used this way. Prefer composition to inheritance. When you do that, it's gonna look like

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