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