12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- #include <iostream>
- using namespace std;
- class Complex {
- private:
- double real;
- double imag;
- public:
- Complex(double r = 0, double i = 0) : real(r), imag(i) {}
- Complex operator+(const Complex& other) const {
- return Complex(real + other.real, imag + other.imag);
- }
- Complex operator-(const Complex& other) const {
- return Complex(real - other.real, imag - other.imag);
- }
- friend ostream& operator<<(ostream& os, const Complex& num) {
- os << num.real << "+i" << num.imag;
- return os;
- }
- Complex operator+(double value) const {
- return Complex(real + value, imag);
- }
- Complex operator-(double value) const {
- return Complex(real - value, imag);
- }
- friend Complex operator+(double value, const Complex& num);
- friend Complex operator-(double value, const Complex& num);
- };
- Complex operator+(double value, const Complex& num) {
- return Complex(value + num.real, num.imag);
- }
- Complex operator-(double value, const Complex& num) {
- return Complex(value - num.real, -num.imag);
- }
- int main() {
- Complex a(2, 5), b(7, 8), c(0, 0);
- c = a + b;
- cout << c << endl;
- c = 4.1 + a;
- cout << c << endl;
- c = b - 5.6;
- cout << c << endl;
- return 0;
- }
|