Member access operators: . and ->
Syntax
postfix-expression:
postfix-expression . templateopt id-expression
postfix-expression -> templateopt id-expression
Remarks
The member access operators . and -> are used to refer to members of struct, union, and class types. Member access expressions have the value and type of the selected member.
There are two forms of member access expressions:
In the first form,
postfix-expressionrepresents a value ofstruct,class, oruniontype, andid-expressionnames a member of the specifiedstruct,union, orclass. The value of the operation is that ofid-expressionand is an l-value ifpostfix-expressionis an l-value.In the second form,
postfix-expressionrepresents a pointer to astruct,union, orclass, andid-expressionnames a member of the specifiedstruct,union, orclass. The value is that ofid-expressionand is an l-value. The->operator dereferences the pointer. The expressionse->memberand(*(e)).member(whereerepresents 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++ built-in operators, precedence, and associativity
Classes and Structs
Structure and union members
Maklum balas
Kirim dan lihat maklum balas untuk