this指標是允許依靠返回該類物件的引用值來連續呼叫該類的成員函式
阿新 • • 發佈:2018-12-23
#include<iostream> using namespace std; class date { int year; int month; public: date() { year=0; month=0; } date& setyear(int yr) { year=(yr<=2008)?yr:0; return *this; } date& setmonth(int mn) { month=(mn>0&&mn<=12)?mn:0; return *this; } void print_date() const; }; void date::print_date() const { cout<<year<<"年"<<month<<"月"<<endl; } int main() { date obj; cout<<"We have got:"; obj.setyear(2008).setmonth(10).print_date(); obj.print_date(); }
We have got:2008年10月
2008年10月
在以上程式中的三個成員函式setHour(), setMinute( )和setSecond()中都使用語句return *this;,將this所指向的物件t返回給主函式。由於園點運算子(.)的結合率為從左向右,因此表示式obj.setmonth( 10 )的執行結果是返回obj,主程式最後語句順序地執行了四條語句:
obj.setyear(2008).
setmonth(10)
.print_date();
這體現了連續呼叫的特點。
date& setyear(int yr)和 date& setmonth(int mn)返回值是物件的引用,呼叫函式只是複製地址,並不複製物件,也不產生新的臨時物件,主函式呼叫和修改只是同一個物件。We have got:2008年10月#include<iostream> using namespace std; class date { int year; int month; public: date() { year=0; month=0; } date setyear(int yr) { year=(yr<=2008)?yr:0; return *this; } date setmonth(int mn) { month=(mn>0&&mn<=12)?mn:0; return *this; } void print_date() const; }; void date::print_date() const { cout<<year<<"年"<<month<<"月"<<endl; } int main() { date obj; cout<<"We have got:"; obj.setyear(2008).setmonth(10).print_date(); obj.print_date(); }
2008年0月
--------------------------------
Process exited after 5.394 seconds with return value 0
請按任意鍵繼續. . .
date setyear(int yr)和 date setmonth(int mn)返回值是物件,每次都要建立新的物件。
this指標不在指向單一的物件,而是指向不同的物件。