65,210
社区成员
发帖
与我相关
我的任务
分享#include<iostream>
#include <iostream>
using namespace std;
class Complex {
public:
Complex (int r = 0, int i = 0) : m_r (r), m_i (i) {}
/*
Complex operator+ (const Complex& c) const {
return Complex (m_r + c.m_r, m_i + c.m_i);
}
*/
friend Complex operator+ (const Complex& c1, const Complex& c2) {
return Complex (c1.m_r + c2.m_r, c1.m_i + c2.m_i);
}
Complex operator+ (int n) {
return Complex (m_r + n, m_i);
}
Complex operator- (const Complex& c) const {
return Complex (m_r - c.m_r, m_i - c.m_i);
}
/*
Complex& operator+= (const Complex& c) {
// return *this = *this + c;
m_r += c.m_r;
m_i += c.m_i;
return *this;
}
*/
friend Complex& operator+= (Complex& c1, const Complex& c2) {
return c1 = c1 + c2;
}
Complex& operator-= (const Complex& c) {
return *this = *this - c;
}
Complex operator- (void) {
return Complex (-m_r, -m_i);
}
const Complex operator++ (int) {
Complex c = *this;
m_r++;
m_i++;
return c;
}
Complex& operator++ (void) {
m_r++;
m_i++;
return *this;
}
const Complex operator-- (int) {
Complex c = *this;
m_r--;
m_i--;
return c;
}
Complex& operator-- (void) {
m_r--;
m_i--;
return *this;
}
private:
int m_r;
int m_i;
friend ostream& operator<< (ostream&, const Complex&);
friend istream& operator>> (istream&, Complex&);
};
ostream& operator<< (ostream& os, const Complex& c) {
os << "(" << c.m_r << "+" << c.m_i << "i)";
return os;
}
istream& operator>> (istream& is, Complex& c) {
return is >> c.m_r >> c.m_i;
}
int main (void) {
Complex c1 (3, 4);
cout << c1 << endl; // operator<<(cout,c1)
// operator<<(cout,c1).operator<<(endl);
Complex c2 (5, 6);
// cin >> c2; // operator>> (cin, c2)
Complex c3 = c1 + c2;
// c3 = c1.operator+ (c2)
// c3 = operator+ (c1, c2)
cout << c1 << '+' << c2 << '=' << c3 << endl;
cout << c3 << '-' << c2 << '=' <<c3-c2<<endl;
Complex c4 (c1);
(c4 += c2) += c2;
// c4.operator+= (c2);
// operator+= (c4, c2);
cout << c4 << endl;
(c4 -= c2) -= c2;
cout << c4 << endl;
cout << -c4 << endl;
int n = 10;
cout << n++ << endl; // 10
cout << n << endl; // 11
// (n++)++;
int m = 10;
cout << ++m << endl; // 11
cout << m << endl; // 11
++++m;
cout << m << endl;
cout << c1++ << endl;
// c1.operator++ (0)
cout << c1 << endl;
// c1++++;
cout << ++c2 << endl;
cout << c2 << endl;
++++c2;
cout << c2 << endl;
cout << c2+100 << endl; // c2.operator+(100)
return 0;
}
#include<iostream>……#include<iostream>#include<iostream>