[問題] 重載運算子

看板C_and_CPP (C/C++)作者 (生活以下)時間16年前 (2009/04/06 21:49), 編輯推噓1(103)
留言4則, 2人參與, 最新討論串1/3 (看更多)
float.h #ifndef FLOAT_H #define FLOAT_H #include <iostream> using namespace std; class Float { friend void printFloat(Float); private: float F; public: Float(): F(0) {} Float(float x): F(x) {} Float operator+=(Float &FF) { F+=FF.F; return F; } operator float() { return F; } }; #endif TestF.cpp #include "Float.h" int main() { Float F1(1.2), F2(3.9); cout << F1 << endl; cout << F2 << endl; cout << "F1+F2=" << F1+F2 << endl; cout << "F1*F2=" << F1*F2 << endl; cout << "F1+=F1 " << (F1+=F1) << endl; system("pause"); } 這個程式執行起來沒問題 但我有兩個問題 1. 我沒有定義 operator+() 跟 operator*() 卻可以使用 F1+F2 跟 F1*F2 這樣是正常的嗎? 2. 一定要定義轉換運算子operator float()才能使用重載運算子嗎? 還是有其他不需要使用operator float()就可以使用重載運算子的方法? 感謝您的解答 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.42.210.177

04/06 22:00, , 1F
1.Float先被轉型成float才匹配到+和*
04/06 22:00, 1F

04/06 22:01, , 2F
2.完全無關
04/06 22:01, 2F

04/07 01:27, , 3F
可是我把operator float()去掉就編譯不過了 怎麼會無關?
04/07 01:27, 3F

04/07 01:42, , 4F
看一下LPH66的回文
04/07 01:42, 4F
文章代碼(AID): #19sWXTZX (C_and_CPP)
討論串 (同標題文章)
以下文章回應了本文
完整討論串 (本文為第 1 之 3 篇):
1
4
文章代碼(AID): #19sWXTZX (C_and_CPP)