Struct initialization of the C/C++ programming language?(C/C++ 编程语言的结构初始化?)
问题描述
我可以用代码进行结构初始化:
I could do struct initialization with code:
struct struct_type_id struct_name_id = { value1, value2, value3 };
但不能:
struct struct_type_id struct_name_id;
struct_name_id = { value1, value2, value3 };
为什么我用前者可以,而用gcc、g++、vc2008、vc6就不能用后者?换句话说,为什么c/c++编程语言不支持这种语法?
why I could do it with the former,but could not with the latter with gcc,g++,vc2008,vc6?In other words,why the c/c++ programming language do not support this syntax?
谢谢.
推荐答案
第一条语句创建了一个初始化为给定值的变量,即,这些值被构建在内存中并直接存储在该变量地址中的程序可执行文件中(对于全局变量)或准备好进行内存复制(用于堆栈变量).
The first statement creates a variable initialized to the given values, i.e., these values are built in memory and stored directly in the program executable in that variable address (for globals) or ready for memory copy (for stack variables).
第二块的第二条语句很不一样.虽然看起来很像,但它是一个赋值表达式.这意味着等号运算符的 RHS 是一个表达式,它被评估(独立于 = 的 LHS 中的内容),然后传递给 = 运算符.没有适当的上下文,{...} 没有任何意义.
The second statement of the second block is very different. Although it looks similar, it is an assign expression. It means that the RHS of the equals operator is an expression that is evaluated (independently of what is in the LHS of =), and then passed to the = operator. Without proper context, {...} doesn't have any meaning.
在 C99 中,您可以这样做:
In C99, you can do this:
struct_name_id = (struct struct_type_id){ value1, value2, value3 };
现在等号运算符的 RHS 是一个有效的表达式,因为编译器有适当的上下文可以知道 {...} 中的内容.
Now the RHS of the equals operator is a valid expression, since there is proper context for the compiler to know what is in {...}.
在 C++11 中,语法是:
In C++11, the syntax is:
struct_name_id = struct_type_id{ value1, value2, value3 };
这篇关于C/C++ 编程语言的结构初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C/C++ 编程语言的结构初始化?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
