C++ : 复数运算“<<”函数重载和“+”、“—”重载

自己最近写了下C++里面的"<<"和"+","-","*","/"运算符重载

#include<iostream>
using namespace std;

class Complex
{
public:
	Complex(double r=0, double i=0):real(r), image(i){}
	Complex operator+(Complex &c);
	Complex operator-(Complex &c);
	Complex operator*(Complex &c);
	Complex operator/(Complex &c);
	friend ostream & operator<<(ostream &, Complex &);

private:
	double real;
	double image;
};
ostream & operator<<(ostream &output, Complex &c)
{
    output<<"(" <<c.real << "+" <<c.image <<"i)" << endl;
    return output;
}

Complex Complex::operator +(Complex &c)
{
	return Complex(real+c.real, image+c.image);
}

Complex Complex::operator -(Complex &c)
{
	return Complex(real-c.real, image-c.image);
}
Complex Complex::operator *(Complex &c)
{
	return Complex(real*c.real-image*c.image, real*c.image+image*c.real);
}
Complex Complex::operator /(Complex &c)
{
	return Complex(real/c.real, image/c.image);
}

int main()
{
	Complex c1(3, 4), c2(5, 10), c3, c4 , c5, c6;
	c3=c1+c2;
	c4=c2-c1;
	c5=c1*c2;
	c6=c2/c1;
    cout << c3 << c4 << c5 << c6;
	return 0;
}


 

猜你喜欢

转载自blog.csdn.net/allesa/article/details/8932653