以複數相加相乘為例,input兩個複數,output運算結果
Operator overloading,兩個方法:1、friend function 2、member function
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class ComplexNumber
{
friend ostream &operator<<( ostream &, ComplexNumber & );
public:
ComplexNumber(int _real, int _imagin)
{
real = _real;
imagin = _imagin;
}
ComplexNumber(){}
ComplexNumber &operator+(ComplexNumber &c)
{
ComplexNumber *tmp;
tmp->real = real + c.real;
tmp->imagin = imagin + c.imagin;
return *tmp;
}
ComplexNumber &operator*(ComplexNumber &c)
{
ComplexNumber *tmp;
tmp->real = (real * c.real) - (imagin * c.imagin);
tmp->imagin = ((real * (c.imagin)) + (imagin * (c.real)));
return *tmp;
}
private:
int real;
int imagin;
};
ostream &operator<<( ostream &out, ComplexNumber &number )
{
out << number.real << " +(" << number.imagin << ")i" << endl;
return out;
}
int main()
{
int a,b,c,d;
cout<< "key in the real number of complex: "<<endl;
cin>>a;
cout<< "key in the imaginary number of complex: "<<endl;
cin>>b;
ComplexNumber obj01(a,b);
cout<< "key in the real number of complex: "<<endl;
cin>>c;
cout<< "key in the imaginary number of complex: "<<endl;
cin>>d;
ComplexNumber obj02(c,d);
ComplexNumber add,mult;
add = obj01 + obj02;
mult = obj01 * obj02;
cout<<"Addition: "<<add;
cout<<"multiplication: "<<mult;
return 0;
}
/**(a+bi)+(c+di) = (a+c)+(b+d)i**/
/**(a+bi)*(c+di) = (ac-bd)+(ad+bc)i**/
留言列表