改:今天看到的一个有趣面试题:return *this和return this有什么区别?
原文地址:https://blog.csdn.net/stpeace/article/details/22220777
說說為什么我要再寫一篇文章,近些年學習編程的路上,深受各種錯誤翻譯和一些錯誤理解的干擾,于是希望給后來人能指引一條爭確的路,起碼不誤導他們,所以看到講的不清楚不對的忍不住要寫點東西。
下邊是原文:
?別跟我說, return *this返回當前對象, return this返回當前對象的地址(指向當前對象的指針)。
??????正確答案為:return *this返回的是當前對象的克隆或者本身(若返回類型為A, 則是克隆, 若返回類型為A&, 則是本身 )。return this返回當前對象的地址(指向當前對象的指針), 下面我們來看看程序吧:
#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;
}
??????結果為:yes
??????再看:
#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返回的是當前對象本身(也就是其引用), 而非副本。
---------------------?
版權聲明:本文為CSDN博主「stpeace」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/stpeace/article/details/22220777
?
?
下邊是我的一些想法:return this;返回的就是當前對象的指針,這個沒什么好說的;
但是,當當當,重點來了,return *this;這個返回的究竟是什么呢,聲明返回類型時怎么寫呢,結論來了,有兩種寫法
A? get()//這樣寫返回的就是一個拷貝,地址和原來對象地址不一樣了
{
return *this;
}
?
或者
A& get()//這樣寫返回的就是一個引用,返回的就是原來的對象
{
return *this;
}
?
總結
以上是生活随笔為你收集整理的改:今天看到的一个有趣面试题:return *this和return this有什么区别?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt程序运行提示“it could no
- 下一篇: QString和string互相转换乱码