复数类

按照课本上的要求实现了一下复数类,若有不正确或不足之处,请指出。

#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++上编译失败。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值