通过重载运算符实现复数的相关据算,通过实现复数这一数学概念来学习和理解如何使用C++运算符重载。
#include <iostream>
using namespace std;
template<class T=float>
class Complex
{
public:
Complex(){}
Complex(const T &real) : _real(real){}
Complex(const T &real, const T &image) : _real(real), _image(image){}
Complex(const Complex &obj) : _real(obj._real), _image(obj._image){}
const Complex& operator=(const Complex &obj){
_real = obj._real;
_image = obj._image;
return *this;
}
friend Complex operator+(const Complex &obj1, const Complex &obj2){
return Complex(obj1._real + obj2._real, obj1._image + obj2._image);
}
friend Complex operator+(const T &a, const Complex &obj2){
return Complex(a + obj2._real, obj2._image);
}
friend Complex operator+(const Complex &obj1, const T &a){
return Complex(obj1._real + a, obj1._image);
}
friend Complex operator-(const Complex &obj1, const Complex &obj2){
return Complex(obj1._real - obj2._real, obj1._image - obj2._image);
}
friend Complex operator-(const T &a, const Complex &obj2){
return Complex(a - obj2._real, - obj2._image);
}
friend Complex operator-(const Complex &obj1, const T &a){
return Complex(obj1._real - a, obj1._image);
}
friend Complex operator*(const Complex &obj1, const Complex &obj2){
T numerator_real = obj1._real*obj2._real - obj1._image*obj2._image;
T numerator_image = obj1._image*obj2._real + obj1._real*obj2._image;
return Complex(numerator_real, numerator_image);
}
friend Complex operator*(const T &a, const Complex &obj){
return Complex(a*obj._real, a*obj._image);
}
friend Complex operator*(const Complex &obj, const T &a){
return Complex(obj._real*a, obj._image*a);
}
friend Complex operator/(const Complex &obj1, const Complex &obj2){
T denominator = obj2._real*obj2._real + obj2._image*obj2._image;
T numerator_real = obj1._real*obj2._real + obj1._image*obj2._image;
T numerator_image = obj1._image*obj2._real - obj1._real*obj2._image;
return Complex(numerator_real / denominator, numerator_image / denominator);
}
friend Complex operator/(const T &a, const Complex &obj){
T denominator = obj._real*obj._real + obj._image*obj._image;
T numerator_real = a*obj._real;
T numerator_image = -a*obj._image;
return Complex(numerator_real / denominator, numerator_image / denominator);
}
friend Complex operator/(const Complex &obj, const T &a){
return Complex(obj._real / a, obj._image / a);
}
friend T arg(const Complex &obj){
return atan2(obj._image, obj._real);
}
friend T abs(const Complex &obj){
return sqrt(obj._real*obj._real + obj._image*obj._image);
}
friend ostream& operator<<(ostream &out, const Complex &obj){
if (obj._image>0){
out << obj._real << " + " << obj._image << "i";
}
else{
out << obj._real << " - " << -obj._image << "i";
}
return out;
}
public:
T _real, _image;
};
int main(int argc, char** argv){
Complex<float> a(1, 2);
Complex<float> b(3, 4);
Complex<float> c;
c = (2 - 2 * (b - a) * 0.5 / a / 2 / b + 8 - 10)*-1;
cout << c << endl;
cout << abs(c) << endl;
cout << arg(c)*180.f/3.1415926f << endl;
return EXIT_SUCCESS;
}
实验结果: