`在C ++中没有命名类型错误 [英] `does not name a type` error in C++

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

问题描述

我不知道要搜索什么来找到这个的解释,所以我问。

我有这个代码,报告错误:

  struct设置{
int width;
int height;
}设置;

settings.width = 800; //'settings'没有命名类型错误
settings.height = 600; //'settings'没有指定类型错误

int main(){
cout< settings.width<< < settings.height< endl;

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

  struct设置{
int width;
int height;
}设置;

main(){
settings.width = 800; //没有错误
settings.height = 600; //没有错误

你能解释一下为什么吗?



EDIT:

关于Ralph Tandetzky的回答,这里是我的完整结构代码。

 结构设置{
struct Dimensions可以显示如何为我的代码段结构分配值{
int width;
int height;
} screen;

struct Build_menu:Dimensions {
int border_width;
} build_menu;
}设置;


解决方案

C ++。如果你对有时看到 = 符号在函数上下文之外使用的事实感到困惑,例如:

  int x = 42; //< ==这不是分配! 

int main()
{
// ...
}

这是因为 = 符号也可以用于初始化。在您的示例中,您不是初始化数据成员 width height ,您正在为它们分配一个值。 / p>

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;

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?

EDIT:
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;

解决方案

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.

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

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