[問題] 樣板類別 的 運算子重載

看板C_and_CPP作者 (Charlott.HonG)時間8年前 (2016/05/31 19:37), 8年前編輯推噓3(303)
留言6則, 3人參與, 最新討論串1/1
請問樣板類別的運算子重載該怎麼寫呢 參考自 http://goo.gl/0lihn8 我試著在自己加上樣板結果出來編不過 程式碼 https://gist.github.com/anonymous/0f2c51e9fb4d9a85406e39044eb370a4 註解的地方有[17][36][80] (錯誤的地方) 我想要做分數的相加,用frac儲存分數 frac<double> a(1,3); frac<double> b(1,2); frac<double> temp; temp=a+b; //temp=5/6 編譯使用G++,錯誤訊息是 error.cpp:17:48: error: 'frac<T1> frac<T1>::operator+(const frac<T1>&, const frac<T1>&)' must take either zero or one argument frac operator+(const frac &a, const frac &b); ^ error.cpp:82:1: error: 'frac<T1>::frac' names the constructor, not the type frac<T1>::frac operator+(const frac &a, const frac &b){ ^ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 120.117.72.133 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1464694628.A.F8D.html

05/31 19:49, , 1F
a+b 的意思是 a.operator+(b) 所以無法接兩個參數
05/31 19:49, 1F
痾 看得懂邏輯,不過不太懂你意思 意思是不能用 temp=a+b 這樣嗎? 只能用a+b;(a存結果)的意思嗎? ※ 編輯: hunandy14 (120.117.72.133), 05/31/2016 20:20:23

05/31 20:42, , 2F
不是, 是你的函數只需要吃一個參數, 另一個參數是 *this
05/31 20:42, 2F
是這個樣子嗎,還是有錯誤,還有哪裡漏掉了嗎 https://goo.gl/ZTU34r ※ 編輯: hunandy14 (120.117.72.133), 05/31/2016 21:14:51

05/31 21:49, , 3F
是 frac<T1> frac<T1>::operator+(...)
05/31 21:49, 3F
是說82行嗎~還是不行QQ error.cpp:82:1: error: 'frac<T1>::frac' names the constructor, not the type frac<T1>::frac<T1> operator+(const frac &b){ ^ error.cpp:82:1: error: and 'frac<T1>' has no template constructors [Finished in 0.2s with exit code 1] ※ 編輯: hunandy14 (114.35.139.127), 05/31/2016 23:04:30

05/31 23:34, , 4F
連照抄都抄錯- - 仔細看::的位置
05/31 23:34, 4F
天啊~真的耶,眼殘了QQ 不好意思,感謝您的眼睛~~~~ 這次我乖乖複製了,完成了做出來了~~~~~~ 開心~謝謝你們~完成的程式碼:https://goo.gl/4vk64q ※ 編輯: hunandy14 (114.35.139.127), 06/01/2016 00:10:35

06/01 01:08, , 5F
XD 可是你實作裡怎麼又指定 frac<double> ??
06/01 01:08, 5F

06/01 01:08, , 6F
照理說不是應該是 frac<T1> 嗎
06/01 01:08, 6F
ㄚㄚ我後來繼續完成後面的功能有發現,怪怪的XDD有修正了 貼的時候還沒發現~感謝您的提醒 修正版:https://goo.gl/aivkOd ※ 編輯: hunandy14 (114.35.139.127), 06/01/2016 01:57:59
文章代碼(AID): #1NJNTa-D (C_and_CPP)