Giả sử chúng ta có lớp số phức với phần thực và phần ảo. Nạp chồng toán tử + để cộng hai số phức. Định nghĩa hàm to_string() trả về biểu diễn chuỗi.
Ví dụ: c1 = 8 - 5i, c2 = 2 + 3i → kết quả: (10 - 2i)
Giải thuật
- Nạp chồng operator+(Complex c2)
- Tạo Complex ret với real = 0, imag = 0
- ret.real = real + c2.real
- ret.imag = imag + c2.imag
- Trả về ret
- to_string(): dùng stringstream, xử lý dấu +/- cho phần ảo
Ví dụ minh họa
#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();
}
Đầu vào
c1(8,-5), c2(2,3)
Đầu ra
(10 - 2i)