推 ko27tye: 比較符合你需求的做法是overload operator() 但使用起來07/24 17:24
→ ko27tye: 會像這樣--> if(a()){...}07/24 17:25
不行,這不符合需求,這我有想過~
a 不能變成 a()
推 bibo9901: 就 operator bool() 啊XD07/24 17:30
沒有很懂><
推 jerryh001: 重載轉型成bool的operator?07/24 17:31
→ jerryh001: 慢了XD07/24 17:31
※ 編輯: OfficeGL (114.137.108.25 臺灣), 07/24/2019 18:15:50
推 s4300026: 就是if(cin),對吧 XD07/24 18:16
→ Lipraxde: conversion operator07/24 18:16
推 LPH66: if(a) 這種式子會把 a 轉型成 bool 再做判斷07/24 19:54
→ LPH66: 所以你只要重載當它轉型成 bool 時的行為即可07/24 19:54
→ LPH66: 要轉成的值即是所有你要使 if(a) 成立的狀況07/24 19:55
→ eye5002003: bibo說的就是你想要的07/25 00:57
可以了~~~ 感謝大家幫助
不過我可以在提問一下嗎?
conversion operator, ex. operator double() / bool() / int() ..
這樣不就根本不需要多載 + - * / && or 了嗎~
class ball { /* declare */ }
int main(){
ball a, b;
int sum = a + b; // 這樣可以 work 椰!! 我根本沒多載 operator +
}
太厲害了~~ 還是我有誤會呢
※ 編輯: OfficeGL (114.137.202.175 臺灣), 07/25/2019 13:33:34
→ sarafciel: 你要的那個operator+不見得什麼場合都會是整數的+呀XD07/25 13:51
→ sarafciel: 最簡單的例子就是std::string07/25 13:53
推 LPH66: 簡單講就是當你的 operator + - * / 等等的運算結果07/25 17:35
→ LPH66: 會需要是某個非內建型態的東西的時候07/25 17:35
→ LPH66: 你不管用什麼中間型態過渡都是沒辦法的07/25 17:36
→ LPH66: 數的運算的例子例如表示有理數的 class07/25 17:36
→ LPH66: 跟數無關的例如上面提的字串相連07/25 17:37
瞭解了~~ 非常謝謝解說
※ 編輯: OfficeGL (114.137.202.175 臺灣), 07/25/2019 18:31:03
推 CoNsTaR: 看 operator + 還是 operator int 的成本大吧 07/28 12:42