结构和联合成员Structure and Union Members

“成员选择表达式”是指结构和联合的成员。A "member-selection expression" refers to members of structures and unions. 此类表达式具有选定成员的值和类型。Such an expression has the value and type of the selected member.


postfix-expression  
.  
identifier  
postfix-expression  
->  
identifier  

此列表描述了成员选择表达式的两种形式:This list describes the two forms of the member-selection expressions:

  1. 在第一种形式中,postfix-expression 表示 structunion 类型的值,而 identifier 为指定的结构或联合的成员命名。In the first form, postfix-expression represents a value of struct or union type, and identifier names a member of the specified structure or union. 运算的值是 identifier 的值且是一个左值(如果 postfix-expression 是左值)。The value of the operation is that of identifier and is an l-value if postfix-expression is an l-value. 有关详细信息,请参阅左值和右值表达式See L-Value and R-Value Expressions for more information.

  2. 在第二种形式中,postfix-expression 表示指向结构或联合的指针,而 identifier 命名指定的结构或联合的成员。In the second form, postfix-expression represents a pointer to a structure or union, and identifier names a member of the specified structure or union. 该值是 identifier 的值且是一个左值。The value is that of identifier and is an l-value.

    成员选择表达式的两种形式具有类似的效果。The two forms of member-selection expressions have similar effects.

    实际上,如果句点前面的表达式由适用于指针值的间接寻址运算符 (\) 构成,则包含成员选择运算符 (->) 的表达式是使用句点 (.) 的表达式的速记版。In fact, an expression involving the member-selection operator (->) is a shorthand version of an expression using the period (.) if the expression before the period consists of the indirection operator (****) applied to a pointer value. 因此,Therefore,


expression  
->  
identifier  

等效于is equivalent to


(*  
expression  
) .  
identifier  

expression 为指针值时。when expression is a pointer value.

示例Examples

以下示例引用此结构声明。The following examples refer to this structure declaration. 有关这些示例中使用的间接寻址运算符 (\) 的信息,请参阅间接寻址运算符和 Address-of 运算符For information about the indirection operator (****) used in these examples, see Indirection and Address-of Operators.

struct pair   
{  
    int a;  
    int b;  
    struct pair *sp;  
} item, list[10];  

item 结构的成员选择表达式与下面类似:A member-selection expression for the item structure looks like this:

item.sp = &item;  

在上面的示例中,将 item 结构的地址分配给结构的 sp 成员。In the example above, the address of the item structure is assigned to the sp member of the structure. 这意味着,item 包含一个指向自身的指针。This means that item contains a pointer to itself.

(item.sp)->a = 24;  

在此示例中,将指针表达式 item.sp 与成员选择运算符 (->) 一起使用以便将值赋给成员 aIn this example, the pointer expression item.sp is used with the member-selection operator (->) to assign a value to the member a.

list[8].b = 12;  

此语句演示如何从结构数组中选择单个结构成员。This statement shows how to select an individual structure member from an array of structures.

另请参阅See Also

成员访问运算符:. 和 ->Member Access Operators: . and ->