Re: [問題] overloading +

看板C_and_CPP作者 (Aider)時間14年前 (2011/12/28 20:52), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《FableKevinS (FableKevinS)》之銘言: : 標題: [問題] overloading + : 時間: Wed Dec 28 20:12:13 2011 : : 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) : c++ : : 問題(Question): : 設 a 是一個物件, 怎麼overload "+" 使得 1 + a 是合法的? : : : : 補充:如果是 a+1 的話可以這樣寫: : : Class Class::operator+(int x){ : Class a; : a.variable = variable + x; : return a; : } : : 那 1+a呢? : : : -- : ※ 發信站: 批踢踢實業坊(ptt.cc) : ◆ From: 140.112.241.250 : → stimim:http://ideone.com/ij0mk 12/28 20:31 : → FableKevinS:那怎麼寫在class呢? 12/28 20:41 當然不能寫在 class class 的 member function 有分有無 常數(const) 也就是 Type member_fn( ... ); 與 Type member_fn( ... ) const ; 假設這兩個在 class FOO; 中 那呼叫就是 FOO foo01; const FOO foo02; foo01.member_fn(...); //呼叫非 const 版本 foo02.member_fn(...); //呼叫 const 版本 如果要與 global function 相對照的話 大概就像 Type member_fn( FOO& f, ... ); 跟 Type member_fn( const FOO& f, ... ); 那你知道為何 operator+ 要寫成 global 了嗎? 因為寫成 member 的話就等於是把第一個參數綁成 a 的型別 那當然沒辦法執行 1 + a (除非有隱式轉型) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.115.202.50

12/28 21:33, , 1F
...這和 const 有啥關係?
12/28 21:33, 1F
兩種可能狀況一起介紹咩,不要太在意XD

12/28 22:15, , 2F
thanks
12/28 22:15, 2F
※ 編輯: WJAider 來自: 140.115.202.50 (12/28 22:53)
文章代碼(AID): #1E-n4OZh (C_and_CPP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #1E-n4OZh (C_and_CPP)