“ Y不命名类型” C ++中的错误 [英] "Y does not name a type" error in C++
问题描述
我不知道要搜索什么来找到对此的解释,所以我要问。
我有此代码报告了错误:
结构设置{
int width;
int高度;
}设置;
settings.width = 800; //设置未将类型错误命名为
settings.height = 600; //设置未将类型错误命名为
int main(){
cout<< settings.width<< << settings.height<<恩德尔
但是如果我将值赋值放在main中,它将起作用:
结构设置{
int width;
int高度;
}设置;
main(){
settings.width = 800; //没有错误
settings.height = 600; //没有错误
你能解释一下为什么吗?
编辑:
关于Ralph Tandetzky的回答,这是我的完整结构代码。您能告诉我如何分配代码段结构吗?
结构设置{
结构尺寸{
int width;
int高度;
}屏幕;
结构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.
这篇关于“ Y不命名类型” C ++中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!