重温操算符重载(一)

话说上次写运算符重载还是在大二,今天算是复习了
#include<iostream>
#include<math.h>
#include<string>

using namespace std;
/*
运算符重载 
*/
class Complex
{
public:
	Complex();
	Complex(double);
	Complex(double, double);
	
	double getReal();
	double getImag();
	void setReal(double curReal);
	void setImag(double curImag);
	void showComplex();
	Complex operator+ (const Complex &)const;
	Complex operator- (const Complex &)const;
	Complex operator* (const Complex &)const;
	Complex operator/ (const Complex &)const;
//	Complex operator^ (const Complex &, const Complex &);

private:
	double real;
	double imag;
};

Complex::Complex()
{
	real = 0.0;
	imag = 0.0;
}

Complex::Complex(double curReal)
{
	real = curReal; 
	imag = 0.0;
}

Complex::Complex(double curReal, double curImag)
{
	real = curReal;
	imag = curImag;
}

double Complex::getReal()
{
	return this->real;
}

double Complex::getImag()
{
	return this->imag;
}

void Complex::setReal(double curReal)
{
	this->real = curReal;
}

void Complex::setImag(double curImag)
{
	this->imag = curImag;
}

void Complex::showComplex()
{
	cout << this->real << " + " << this->imag << "i" << endl;
}
//const 用的不够熟练
Complex Complex:: operator+ (const Complex &c)const
{
	/*报错:l-value specifies const object
	real = real + c.real;
	imag = imag + c.imag;
	*/
	Complex newComplex(real+c.real, imag+c.imag);
	return newComplex;
}

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

Complex Complex::operator* (const Complex &c)const
{
	Complex newComplex(real*c.real-imag*c.imag, real*c.imag+imag*c.real);
	return newComplex;
}

Complex Complex::operator/ (const Complex &c)const
{
	double newReal = (real*c.real-imag*c.imag)/(c.real*c.real+c.imag*c.imag);
	double newImag = (imag*c.real-real*c.imag)/(c.real*c.real+c.imag*c.imag);
	Complex newComplex(newReal ,newImag);
	return newComplex;
}

void test()
{
	Complex c1(2.3, 4.5);
	Complex c2(6.7);
	Complex c3;
	c1.showComplex();
	c2.showComplex();
	c3.showComplex();

	c1 = c1*c2;
	c1.showComplex();

	c1 = c1 + c3;
	c1.showComplex();
	
	c1 = c1 + c2;
	c1.showComplex();

	c1 = c1 - c2;
	c1.showComplex();

	c1 = c1/c2;
	c1.showComplex();
}

int main()
{
	test();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值