// 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;
}
以上代码中会出现编译错误。
In function ‘int main()’:
cc.cpp:15:10: error: base operand of ‘->’ has non-pointer type ‘Date’
mydate->month = 2;
^
cc.cpp:16:42: error: base operand of ‘->’ has non-pointer type ‘Date’
cout << mydate.month << "/" << mydate->day
^
cc.cpp:17:26: error: base operand of ‘->’ has non-pointer type ‘Date’
<< "/" << mydate->year << endl;
^
将代码改成如下方式则顺利通过:
// 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;
}
通过以上两种代码可简单的表述为,当对象为指针时需用“->”进行成员的访问,对象为普通时用“.”访问和赋值。