今天看到的一個有趣面試題:return *this和return this有什麼區別?
阿新 • • 發佈:2019-01-09
別跟我說, return *this返回當前物件, return this返回當前物件的地址(指向當前物件的指標)。
正確答案為:return *this返回的是當前物件的克隆或者本身(若返回型別為A, 則是克隆, 若返回型別為A&, 則是本身 )。return this返回當前物件的地址(指向當前物件的指標), 下面我們來看看程式吧:
結果為:yes#include <iostream> using namespace std; class A { public: int x; A* get() { return this; } }; int main() { A a; a.x = 4; if(&a == a.get()) { cout << "yes" << endl; } else { cout << "no" << endl; } return 0; }
再看:
結果為:#include <iostream> using namespace std; class A { public: int x; A get() { return *this; //返回當前物件的拷貝 } }; int main() { A a; a.x = 4; if(a.x == a.get().x) { cout << a.x << endl; } else { cout << "no" << endl; } if(&a == &a.get()) { cout << "yes" << endl; } else { cout << "no" << endl; } return 0; }
4
no
最後, 如果返回型別是A&, 那麼return *this返回的是當前物件本身(也就是其引用), 而非副本。