问题描述
我在全局范围中定义了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 << '\t' << co.y << '\t' << 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() {}
$ c> typedef 废话是在上个世纪(而不是在C ++中需要)。
Also, that backwards typedef
nonsense is so last century (and not required in C++).
如果你想初始化你的对象,do这:
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 << '\t' << co.y << '\t' << co.t << std::endl;
}
这篇关于不能在全局范围中使用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!