[問題] 有關於 *this 用法

看板C_and_CPP作者 (dada)時間14年前 (2012/02/15 11:50), 編輯推噓0(0019)
留言19則, 6人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) devc++ ,VC2010 問題(Question): *this 這邊很沒feeling 感受不到這斷程式的意義 回傳*this 傳的是什麼內容 沒有*<==只回傳this 是什麼情形 沒有&<==又是什麼情形 程式碼(Code):(請善用置底文網頁, 記得排版) 如 primer p441 頁返回*this用法 在440頁有提到使用時機,當指向整個物件的時候,最常見的情況便是 函式返回其呼叫者的 reference 然後再p441 typedef std::string::size_type index; class Screen{ public: Screen& move(index r,index c); Screen& set(char); Screen& set(index,index,char); }; Screen& Screen::set(char c){ contents[cursor]=c; return *this; } Screen& Screen::move(index r,index c){ index row = r*width; cursor = row +c; return *this; } 補充: 在此我解釋一下我知道的地方 this 為指向class物件,當加上指標"*"時表示回傳instance 回傳後進行物件參造 我不懂 1. 指向哪個物件 以move(index r,index c)為例 是cursor ? 2. 跟涵式內的code跟this又有什麼關聯性 ? 在此先謝謝各位指點 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.125.21.48

02/15 11:55, , 1F
為了可以寫出類似這樣的程式 http://ideone.com/purcC
02/15 11:55, 1F

02/15 11:56, , 2F
至於 * 與 & 你可以拿掉試試,特別注意物件的建立與刪除
02/15 11:56, 2F

02/15 13:20, , 3F
this: pointer to the instance
02/15 13:20, 3F

02/15 13:21, , 4F
*this: the instance
02/15 13:21, 4F

02/15 13:23, , 5F
就是讓函式傳回本身的參考
02/15 13:23, 5F

02/15 15:14, , 6F
對pointer用*號就是取值的意思,所以用在this就是取出物件
02/15 15:14, 6F

02/15 15:16, , 7F
的instance,而不是reference,如果用在函式回傳,
02/15 15:16, 7F

02/15 15:18, , 8F
而沒有加上&(這才是取reference),是會造成物件進行copy的
02/15 15:18, 8F
※ 編輯: wasidada 來自: 140.125.21.48 (02/15 17:27)

02/15 17:28, , 9F
已經亂掉 不知道怎發問了
02/15 17:28, 9F
※ 編輯: wasidada 來自: 140.125.21.48 (02/15 17:30)

02/15 17:33, , 10F
請問如果把*跟&都拿掉是否就沒有進行copy?
02/15 17:33, 10F

02/15 17:50, , 11F
一樣有copy
02/15 17:50, 11F

02/15 18:52, , 12F
這樣不是只回傳pointer?怎麼會有copy,還是說要把
02/15 18:52, 12F

02/15 18:52, , 13F
Screen&改成Screen*才對
02/15 18:52, 13F

02/15 19:00, , 14F
改成Screen*就能用return this傳回"指向物件本身"的指標
02/15 19:00, 14F

02/15 19:01, , 15F
改成Screen然後return *this就是自己複製一份再傳回去
02/15 19:01, 15F

02/15 19:03, , 16F
了解!
02/15 19:03, 16F

02/15 19:16, , 17F
改成 Screen& 然後回傳 return *this 就不會發生 copy
02/15 19:16, 17F

02/15 19:23, , 18F
就以Screen為例,move回傳Screen&是為了讓你這樣寫,
02/15 19:23, 18F

02/15 19:25, , 19F
screen.move(r,c).set('..').set 一直這樣串下去寫
02/15 19:25, 19F
文章代碼(AID): #1FEojpJk (C_and_CPP)