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

语法Syntax

postfix-expression . name
postfix-expression -> name

备注Remarks

成员访问运算符 The member access operators . -> 用于引用的结构、 联合和类成员。and -> are used to refer to members of structures, unions, and classes. 成员访问表达式具有选定成员的值和类型。Member access expressions have the value and type of the selected member.

有两种形式的成员访问表达式:There are two forms of member access expressions:

  1. 在第一种形式,后缀表达式表示的结构、 类或联合类型值和名称命名指定的结构、 联合或类的成员。In the first form, postfix-expression represents a value of struct, class, or union type, and name names a member of the specified structure, union, or class. 操作的值为名称是左值,如果后缀表达式是左值。The value of the operation is that of name and is an l-value if postfix-expression is an l-value.

  2. 在第二个窗体后缀表达式表示指向结构、 联合或类的指针和名称命名指定的结构、 联合或类的成员。In the second form, postfix-expression represents a pointer to a structure, union, or class, and name names a member of the specified structure, union, or class. 值为名称和是左值。The value is that of name and is an l-value. -> 运算符取消引用指针。The -> operator dereferences the pointer. 因此,表达式e->member(*e).member(其中e表示的指针) 会产生相同的结果 (例外运算符->*重载)。Therefore, the expressions e->member and (*e).member (where e represents a pointer) yield identical results (except when the operators -> or * are overloaded).

示例Example

以下示例演示成员访问运算符的两种形式。The following example demonstrates both forms of the member access operator.

// expre_Selection_Operator.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

struct Date {
   Date(int i, int j, int k) : day(i), month(j), year(k){}
   int month;
   int day;
   int year;
};

int main() {
   Date mydate(1,1,1900);
   mydate.month = 2;
   cout  << mydate.month << "/" << mydate.day
         << "/" << mydate.year << endl;

   Date *mydate2 = new Date(1,1,2000);
   mydate2->month = 2;
   cout  << mydate2->month << "/" << mydate2->day
         << "/" << mydate2->year << endl;
   delete mydate2;
}
2/1/1900
2/1/2000

请参阅See also

后缀表达式Postfix Expressions
C++ 内置运算符、优先级和关联性C++ Built-in Operators, Precedence and Associativity
类和结构Classes and Structs
结构和联合成员Structure and Union Members