สมมติว่าเรามีคลาสจำนวน مختلط (Complex) ที่มีส่วนจริง (real) และส่วนจินตภาพ (imag) ต้องโหลดโอเปอเรเตอร์บวก (+) เพื่อบวกจำนวน مختلط 2 ตัว และมีฟังก์ชันแสดงผลในรูปแบบมาตรฐาน
เช่น c1 = 8 - 5i, c2 = 2 + 3i ผลลัพธ์: 10 - 2i
ขั้นตอนการแก้ปัญหา
- โหลดโอเปอเรเตอร์ + รับ Complex c2 เป็นอาร์กิวเมนต์
- สร้าง Complex ret เริ่มต้น 0
- ret.real = real + c2.real
- ret.imag = imag + c2.imag
- คืนค่า ret
- เมธอด to_string() จัดรูปแบบ (real ± imag i)
ตัวอย่างโค้ด
#include <iostream> #include <sstream> #include <cmath> using namespace std; class Complex { private: int real, imag; public: Complex(){ real = imag = 0; } Complex(int r, int i){ real = r; imag = i; } string to_string(){ stringstream ss; if(imag >= 0) ss << "(" << real << " + " << imag << "i)"; else ss << "(" << real << " - " << abs(imag) << "i)"; return ss.str(); } Complex operator+(Complex c2){ Complex ret; ret.real = real + c2.real; ret.imag = imag + c2.imag; return ret; } }; int main(){ Complex c1(8,-5), c2(2,3); Complex res = c1 + c2; cout << res.to_string(); }
อินพุต
c1(8,-5), c2(2,3)
เอาต์พุต
(10 - 2i)