C++运算符重载实验
通过增加新的运算符来提高类的复杂性,在下面已定义好的复数类的基础上,增加重载运算符+,-=,=,/=,++,<<。然后,在主函数中进行测试。操作符重载函数应该被定义为成员函数或友元函数。
#include
using namespace std;
class Complex{
double re, im;
public:
Complex (double r=0, double i=0)
{ re=r; im=i;}
void show();
};
void Complex ::show()
{ cout<<re<<"+"<<im<<“i”<<endl; }
int main()
{
Complex c1(1,2),c2(3,4),c3;
c3=c1+c2; c3.show();
c3-=c1; c3.show();
c3=c1; c3.show();
c3/=c2; c3.show();
c3++; c3.show();
cout<<c1<<endl;
cout<<c2<<endl;
cout<<c3<<endl;
return 0;
}
提示:复数运算法则如下:
加法:(a+bi)+(c+di)=(a+c)+(b+d)i
减法:(a+bi)-(c+di)=(a-c)+(b-d)i
乘法:(a+bi)(c+di)=(ac-bd)+(bc+ad)i
除法:(a+bi)/(c+di)= (ac+bd)/(c2+d2) +(bc-ad)/(c2+d2)i
#include<iostream>
using namespace std;
class Complex
{
double re, im;
public:
Complex(double r = 0, double i = 0)
{
re = r; im = i;
}
Complex operator+(Complex a);
friend Complex& operator-=(Complex& a, Complex& b);
Complex& operator*=(Complex& a);
Complex& operator/=(Complex& a)
{
Complex temp = *this;
this->re = (temp.re * a.re + temp.im * a.im) / (a.re*a.re + a.im * a.im);
this->im = (temp.im * a.re - temp.re * a.im) / (a.re*a.re + a.im * a.im);
return *this;
}
//后置自增
Complex operator++(int)
{
Complex result(*this);
im++;
re++;
return result;
}
friend ostream& operator<<(ostream& out, const Complex& cur)
{
out << cur.re << "+" << cur.im << "i" << endl;
return out;
}
void show();
};
Complex Complex::operator+(Complex a)
{
Complex result;
result.re = this->re + a.re;
result.im = this->im + a.im;
return result;
}
Complex& operator-=(Complex& a, Complex& b)
{
a.im = a.im - b.im;
a.re = a.re - b.re;
return a;
}
Complex& Complex::operator*=(Complex& a)
{
Complex temp = *this;
this->re = temp.re * a.re - temp.im * a.im;
this->im = temp.im * a.re + temp.re * a.im;
return *this;
}
void Complex::show()
{
cout << re << "+" << im << "i" << endl;
}
int main()
{
Complex c1(1, 2), c2(3, 4), c3;
c3 = c1 + c2; c3.show();
c3 -= c1; c3.show();
c3 *= c1; c3.show();
c3 /= c2; c3.show();
c3++; c3.show();
cout << c1 << endl;
cout << c2 << endl;
cout << c3 << endl;
return 0;
}