"Y does not name a type"错误C++

"Y does not name a type" error in C++

本文关键字:type 错误 C++ name does not      更新时间:2023-10-16

我不知道该怎么搜索才能找到这个问题的解释,所以我问。
我有这段代码报告错误:

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;

但是如果我把值赋值放在main中,它可以工作:

struct Settings{
    int width;
    int height;
} settings;
main () {
    settings.width = 800; // no error
    settings.height = 600; // no error

你能告诉我为什么吗?

编辑:


关于Ralph Tandetzky的回答,这里是我的完整结构代码。你能告诉我如何赋值,就像你对我的代码片段结构体做的那样吗?

struct Settings{
    struct Dimensions{
        int width;
        int height;
    } screen;
    struct Build_menu:Dimensions{
        int border_width;
    } build_menu;
} settings;

在c++中不能将赋值置于函数的上下文之外。如果您对有时在函数的上下文中看到=符号被使用感到困惑,例如:

int x = 42; // <== THIS IS NOT AN ASSIGNMENT!
int main()
{
    // ...
}

这是因为=符号也可以用于初始化。在您的示例中,您没有初始化数据成员widthheight,您正在为它们分配一个值。

在c++ 11中可以写

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

来修复你的错误。出现错误是因为您试图在函数体外部赋值。可以在函数外部初始化全局数据,但不能赋值全局数据。

编辑:

关于你的编辑,只需写

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

由于继承的关系,我不能100%确定这是否有效。我建议在这种情况下避免继承,并将Dimensions作为成员数据写入Build_menu结构中。继承迟早会给你带来各种麻烦,当你这样使用的时候。比起继承,更喜欢组合。当你这样做的时候,它看起来会像

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