can#39;t use structure in global scope(不能在全局范围内使用结构)
问题描述
我在全局范围内定义了 struct,但是当我尝试使用它时,我得到错误:'co' 没有命名类型,但是当我在函数中执行相同操作时,一切工作正常
I defined struct in the global scope, but when I try to use it, I get error: ‘co’ does not name a type, but when I do the same in a function, everything works fine
typedef struct {
int x;
int y;
char t;
} MyStruct;
MyStruct co;
co.x = 1;
co.y = 2;
co.t = 'a'; //compile error
void f() {
MyStruct co;
co.x = 1;
co.y = 2;
co.t = 'a';
cout << co.x << ' ' << co.y << ' ' << co.t << endl;
} //everything appears to work fine, no compile errors
我做错了什么,还是结构不能在全局范围内使用?
Am I doing something wrong, or structures just cannot be used in global scope?
推荐答案
并不是说您不能在全局范围内使用结构".这里的结构没有什么特别之处.
It's not that you "can't use structures in global scope". There is nothing special here about structures.
您根本无法编写程序代码,例如函数体之外的赋值.任何对象就是这种情况:
You simply cannot write procedural code such as assignments outside of a function body. This is the case with any object:
int x = 0;
x = 5; // ERROR!
int main() {}
此外,向后 typedef
是上个世纪的废话(在 C++ 中不需要).
Also, that backwards typedef
nonsense is so last century (and not required in C++).
如果您要初始化对象,请执行以下操作:
If you're trying to initialise your object, do this:
#include <iostream>
struct MyStruct
{
int x;
int y;
char t;
};
MyStruct co = { 1, 2, 'a' };
int main()
{
std::cout << co.x << ' ' << co.y << ' ' << co.t << std::endl;
}
这篇关于不能在全局范围内使用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不能在全局范围内使用结构


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01