现在的位置: 首页 > 综合 > 正文

complex 重载 算数运算符

2014年10月13日 ⁄ 综合 ⁄ 共 730字 ⁄ 字号 评论关闭
#include <iostream>
using namespace std;

class complex
{
public:
	friend void print(const complex &c);
	complex();
	complex(double r,double i);
	~complex();
	complex operator+(const complex &c);
	complex operator-(const complex &c);
private:
	double real,imag;
};

complex::complex()
{
	real = imag = 0;
}

complex::complex(double r,double i)
{
	real = r;
	imag = i;
}

complex::~complex()
{

}

complex complex::operator+(const complex &c)
{
	return complex(real + c.real,imag +c.imag);
}

complex complex::operator-(const complex &c)
{
	return complex(real - c.real,imag - c.imag);
}

void print(const complex &c)
{
	if(c.imag <0)
		cout<<c.real<<"-"<<c.imag<<endl;
	else
		cout<<c.real<<"+"<<c.imag<<endl;
}

int main(void)
{
	complex c1(2.0,3.9),c2(4.0,-2.0),c3;
	c3 = c1 + c2;
	cout<<"\n c1 + c2 = :";
	print(c3);
	c3 = c1 - c2;
	cout<<"\n c1 - c2 =";
	print(c3);
	return 0;
}

抱歉!评论已关闭.