按照课本上的要求实现了一下复数类,若有不正确或不足之处,请指出。
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::ostream;
class Complex {
public:
Complex(double, double);
Complex(const Complex&);
void show();
friend Complex operator+(const Complex&, const Complex&);
friend Complex operator-(const Complex&, const Complex&);
Complex& operator=(const Complex&);
Complex & operator++();
Complex operator++(int);
friend ostream & operator <<(ostream&, const Complex&);
friend istream & operator >>(istream&, Complex&);
private:
double real, imag;
};
Complex::Complex(double x = 0, double y = 0) : real(x), imag(y) {}
Complex::Complex(const Complex& p) : real(p.real), imag(p.imag) {}
void Complex::show() {
if (imag == 0) cout << real;
else if (real == 0) cout << imag << 'i';
else if (imag > 0) cout << real << '+' << imag << 'i';
else cout << real << '-' << -imag << 'i';
}
Complex operator+(const Complex &c1, const Complex &c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
Complex operator-(const Complex &c1, const Complex &c2) {
return Complex(c1.real - c2.real, c1.imag - c2.imag);
}
Complex & Complex::operator=(const Complex &c) {
real = c.real;
imag = c.imag;
return *this;
}
Complex & Complex::operator++() {
real++;
return *this;
}
Complex Complex::operator++(int) {
Complex old = *this;
++*this;
return old;
}
ostream & operator<<(ostream &out, const Complex &c) {
if (c.imag == 0) out << c.real;
else if (c.real == 0) out << c.imag << 'i';
else if (c.imag > 0) out << c.real << '+' << c.imag << 'i';
else out << c.real << '-' << -c.imag << 'i';
return out;
}
istream & operator>>(istream &in, Complex &c) {
double x, y;
in >> x >> y;
c = Complex(x, y);
return in;
}
Complex operator""i(unsigned long long y) {
return Complex(0, double(int(y)));
}
Complex operator""i(long double y) {
return Complex(0, double(y));
}
int main() {
Complex p1 = 1 + 5i;
Complex p2 = p1;
cout << p1++ << endl;
cout << ++p2 << endl;
Complex& p3 = p2;
p3 = 5 - 4i;
p3++++;
++++p3;
p3.show();
return 0;
}
程序在Visual Studio 2017上编译通过,在Dev C++上编译失败。