C++ 全局 静态结构体变量的初始化

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ 全局 静态结构体变量的初始化相关的知识,希望对你有一定的参考价值。

static struct ReservedInfo
const string sKey;
const TokenType iToken;
ReservedInfo[MAXRESERVED] =
"function", FUNCDEF,
"NULL", NULLVAL,
"if", IF,
"elseif", ELSEIF,
"else", ELSE,
"while", WHILE,
"break", BREAK,
"continue", CONTINUE,
"return", RETURN,
"atof", FUNCTION,
"ceil", FUNCTION,
"floor", FUNCTION,
"abs", FUNCTION,
"index", FUNCTION,
"substr", FUNCTION,
"strlen", FUNCTION,
"trim", FUNCTION,
"replace", FUNCTION,
"split", FUNCTION,
"printf", FUNCTION
;

这样定义后,编译为何报如下错误:
e:\desktop\script parser\c语言的脚本解析\formula+c%2b%2b(1)\formula c++\formula\parse.cpp(13) : error C2440: 'initializing' : cannot convert from 'char [9]' to 'struct ReservedInfo1'
No constructor could take the source type, or constructor overload resolution was ambiguous
e:\desktop\script parser\c语言的脚本解析\formula+c%2b%2b(1)\formula c++\formula\parse.cpp(13) : error C2440: 'initializing' : cannot convert from 'TokenType' to 'struct ReservedInfo1'
No constructor could take the source type, or constructor overload resolution was ambiguous
e:\desktop\script parser\c语言的脚本解析\formula+c%2b%2b(1)\formula c++\formula\parse.cpp(14) : error C2440: 'initializing' : cannot convert from 'char [5]' to 'struct ReservedInfo1'
No constructor could take the source type, or constructor overload resolution was ambiguous
e:\desktop\script parser\c语言的脚本解析\formula+c%2b%2b(1)\formula c++\formula\parse.cpp(14) : error C2440: 'initializing' : cannot convert from 'TokenType' to 'struct ReservedInfo1'
No constructor could take the source type, or constructor overload resolution was ambiguous

..........

参考技术A typedef struct ReservedInfo
const string sKey;
const TokenType iToken;
RESERVEDINFO;

static RESERVEDINFO stReservedInfo[MAXRESERVED] =
"function", FUNCDEF,
"NULL", NULLVAL,
"if", IF,
"elseif", ELSEIF,
"else", ELSE,
"while", WHILE,
"break", BREAK,
"continue", CONTINUE,
"return", RETURN,
"atof", FUNCTION,
"ceil", FUNCTION,
"floor", FUNCTION,
"abs", FUNCTION,
"index", FUNCTION,
"substr", FUNCTION,
"strlen", FUNCTION,
"trim", FUNCTION,
"replace", FUNCTION,
"split", FUNCTION,
"printf", FUNCTION
;

请问C中结构体变量为全局变量或静态变量时才能初始化么?

参考技术A 但1989年ANSI制订的第一个C标准(通常称为C89)即规定:允许局部动态的结构体变量(或数组)被初始化。
你那本书虽然在2004年才出版,却不符合C89的规定,很是遗憾!
不允许对局部动态的集合类型的对象(如结构体变量,数组)进行初始化,是担心效率太低,比较耗时,因为动态局部变量的初始化在每次进入函数时都要进行。本回答被提问者采纳

以上是关于C++ 全局 静态结构体变量的初始化的主要内容,如果未能解决你的问题,请参考以下文章

请问C中结构体变量为全局变量或静态变量时才能初始化么?

关于C++全局变量和静态变量初始化的一些总结

全局变量和局部变量

结构体变量初始化问题

C++ 如何将一个静态结构体数组初始化?

C++中,类内的成员变量自动初始化为零吗,而全局变量随意赋值