quot;Y does not name a typequot; error in C++(“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()
{
// ...
}
那是因为 = 符号也可以用于初始化.在您的示例中,您没有初始化数据成员 width 和 height,而是为它们分配了一个值.
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++ 中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“Y 未命名类型"C++ 中的错误
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
