问题描述
我不知道要搜索什么才能找到对此的解释,所以我在问.
我有这个报告错误的代码:
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++ 中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)