“Y 未命名类型"C++ 中的错误 [英] "Y does not name a type" error in C++

查看:27
本文介绍了“Y 未命名类型"C++ 中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道要搜索什么才能找到对此的解释,所以我在问.
我有这个报告错误的代码:

I don't know what to search to find an explanation for this, so I am asking.
I have this code which reports error:

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 中,它会起作用:

but if I put the value assignment in main, it works:

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

main () {
    settings.width = 800; // no error
    settings.height = 600; // no error

你能解释一下为什么吗?

Can you explain me why?


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


Regarding to Ralph Tandetzky's answer, here is my full struct code. Could you show me how to assign the values as you did with my snippet struct?

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

    struct Build_menu:Dimensions{
        int border_width;
    } build_menu;
} settings;

推荐答案

在 C++ 中,不能将赋值放在函数的上下文之外.如果您对有时在函数上下文之外使用 = 符号这一事实感到困惑,例如:

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()
{
    // ...
}

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

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.

这篇关于“Y 未命名类型"C++ 中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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