<C++程序设计>——运算符重载(例题)
复数中将双目算术运算符(+,-,*,/)与赋值运算符(+=,-=)重载为友元函数
下面是例题的源代码:
#include <iostream.h>
#include <stdlib.h>
#include <math.h>
class Complex //Complex是复数
{
private:
double real; //real为实部
double imag; //imag为虚部
public:
Complex(double r = 0, double i = 0) //带缺省参数值的构造函数
{
real = r;
imag = i; //对real和imag赋值
}
void print(); //成员函数print()显示real和imag
void operator =(Complex &); //赋值操作
friend Complex operator -(const Complex &); //单目-操作
friend Complex operator +(const Complex & c1, const Complex & c2); //双目 + 操作
friend Complex operator -(const Complex & c1, const Complex & c2); //双目 - 操作
friend Complex operator *(const Complex & c1, const Complex & c2); //双目 * 操作
friend Complex operator /(const Complex & c1, const Complex & c2); //双目 / 操作
friend double norm(const Complex &); //单目操作,求复数的幅值的平方
friend Complex& operator +=(Complex& c1,Complex& c2);//赋值+= 操作
friend Complex& operator -=(Complex& c1,Complex& c2);//赋值 -= 操作
};
void Complex::print()
{
cout<<'('<<real<<'+'<<imag<<"i) "<<endl;
}
void Complex::operator =(Complex & c)
{
real = c.real; imag = c.imag;
}
Complex operator -(const Complex & c)
{
return Complex(-c.real,-c.imag);
}
Complex operator +(const Complex & c1, const Complex & c2)
{
double r = c1.real + c2.real;
double i = c1.imag + c2.imag;
return Complex(r,i);
}
Complex operator -(const Complex & c1, const Complex & c2)
{
double r = c1.real - c2.real;
double i = c1.imag - c2.imag;
return Complex(r,i);
}
Complex operator *(const Complex & c1, const Complex & c2)
{
double r = c1.real * c2.real + c1.imag * c2.imag;
double i = c1.real * c2.imag - c1.imag * c2.real;
return Complex(r,i);
}
Complex operator /(const Complex & c1, const Complex & c2)
{
Complex result;
double den;
den = norm(c2);
if(den>1E-7||den<-1E-7)
{
result.real = ((c1.real * c2.real) - (c1.imag * c2.imag))/den;
result.imag = ((c1.real * c2.real) + (c1.imag * c2.imag))/den;
}
else
{
cout<<" complex / error ! "<<endl;
exit(1);
}
return result;
}
double norm(const Complex & c)
{
double result = (c.real * c.real) + (c.imag * c.imag);
return result;
};
Complex& operator +=(Complex& c1,Complex& c2)
{
c1.real +=c2.real;
c1.imag +=c2.imag;
return c1;
}
Complex& operator -=(Complex& c1,Complex& c2)
{
c1.real -=c2.real;
c1.imag -=c2.imag;
return c1;
}
void main()
{
Complex c1(2.5,3.5),c2(4.5,6.5); //复数 c1 = 2.5+i3.5; c2 = 4.5+i6.5
Complex c;
c = c1 - c2;
c.print();
c = c1 + c2;
c.print();
c = c1 * c2;
c.print();
c = c1 / c2;
c.print();
c1+=c2;
c1.print();
c1-=c2;
c1.print();
}
其运行结果如下:
##程媛小白,学术不精,还望各位多多指导,嘿嘿##