"Y没有在C++中命名类型"错误

Qwe*_*rty 13 c++ struct class variable-assignment

我不知道该搜索什么来找到解释,所以我在问.
我有这个代码报告错误:

struct Settings{
    int width;
    int height;
} settings;

settings.width = 800; // 'settings' does not name a type error
settings.height = 600; // 'settings' does not name a type error

int main(){
    cout << settings.width << " " << settings.height << endl;
Run Code Online (Sandbox Code Playgroud)

但如果我将值赋值放在main中,它的工作原理如下:

struct Settings{
    int width;
    int height;
} settings;

main () {
    settings.width = 800; // no error
    settings.height = 600; // no error
Run Code Online (Sandbox Code Playgroud)

你能解释一下为什么吗?

编辑:
关于Ralph Tandetzky的回答,这是我的完整结构代码.你能告诉我如何像你的片段结构那样分配值吗?

struct Settings{
    struct Dimensions{
        int width;
        int height;
    } screen;

    struct Build_menu:Dimensions{
        int border_width;
    } build_menu;
} settings;
Run Code Online (Sandbox Code Playgroud)

And*_*owl 26

您不能在C++中将赋值放在函数的上下文之外.如果您有时看到=符号在函数的上下文之外使用,例如:

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

int main()
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

那是因为=符号也可以用于初始化.在你的榜样,你是不是初始化数据成员widthheight,你值分配给他们.


Ral*_*zky 9

在C++ 11中,您可以编写

struct Settings {
    int width;
    int height;
} settings = { 800, 600 };
Run Code Online (Sandbox Code Playgroud)

为了修复你的bug.出现错误是因为您尝试在函数体外部分配值.您可以初始化但不能在函数外部分配全局数据.

编辑:

关于你的编辑,只需写

Settings settings = {{800, 600}, {10, 20, 3}};
Run Code Online (Sandbox Code Playgroud)

我不是百分百肯定,如果这样做,但由于继承.我建议在这种情况下避免继承,并将Dimensionsas成员数据写入您的Build_menu结构.当用这种方式时,继承会迟早会给你带来各种麻烦.首选组合继承.当你这样做时,它会是这样的

Settings settings = {{800, 600}, {{10, 20}, 3}};
Run Code Online (Sandbox Code Playgroud)