- 用在:某個class裡面
- 意義:指向自己這個物件的指標
- 注意:他是指標,並非說該物件中又包含該物件自己的遞迴,而只是儲存自己的記憶體位置
故讀取自己class中的變數,有以下幾種方法:
- 直接讀取;如Class (C++)中的studentName
- 讀取指標內的值;如this->studentName
- 先讀取指標指向的物件,再找尋物件中的值;如(*this).studentName
第1種方法是最簡單的,然而在遇到以下列舉的情況時,我們必須透過第2或3的方法才能解決:
- local variable、function argument variable通常優先權高於class variable,即有同名的local variable、function argument variable出現時,就沒辦法用該名字讀到class variable,此時,可以加寫this找尋回class variable
- 串列寫法,如果我們需要回傳物件自己,就會需要用到return *this。
- 串列寫法:myClass.setA(1).setB(2).setC(3)
- setA, setB, setC需要回傳*this方可以讓下一個"."符號串起來
myClass.h
class MyClass{ public: MyClass(int = -1, int = -1, int = -1); // Return the reference of this object MyClass &setA(int); MyClass &setB(int); MyClass &setC(int); void display(); private: int a; int b; int c; };
myClass.cpp
#include <iostream> #include "myClass.h" using namespace std; // constructor MyClass::MyClass(int new_a, int new_b, int new_c){ a = new_a; b = new_b; c = new_c; } // setA MyClass &MyClass::setA(int new_a){ cout << "function argument new_a = " << new_a << endl; a = new_a; return *this; } // setB MyClass &MyClass::setB(int b){ cout << "function argument b = " << b << endl; cout << "this.b = " << this->b << endl; this->b = b; return *this; } // setC MyClass &MyClass::setC(int c){ cout << "function argument c = " << c << endl; cout << "this.c = " << (*this).c << endl; // *this.c is a wrong usage since "this.c" isn't a pointer (*this).c = c; return *this; } // display the member values(a, b, c) void MyClass::display(){ cout << "a=" << a << "\tb=" << b << "\tc" << c << endl; }
main.cpp
#include <iostream> #include "myClass.h" using namespace std; int main(){ // create a new class instance MyClass myClass; // setup myClass.setA(10).setB(3).setC(2); // display it myClass.display(); return 0; }
Thanks for all the helpful insights. we are going to be change this post with new info. This is very a beautiful post. I appreciate your exertions. Keep posting new updates with us.
ReplyDeleteDedicated hosting