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