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;
}
这篇关于不能在全局范围内使用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不能在全局范围内使用结构
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01