完善的复数类
复数类应该具有的操作
运算:+,-,*,/
比较:==,!=
赋值:=
求模:modulus
利用操作符重载
-统一复数与实数的运算方式
-统一复数与实数的比较方式
Complex operator + (const Complex& c);
Complex operator - (const Complex& c);
Complex operator * (const Complex& c);
Complex operator / (const Complex& c);
bool operator == (const Complex& c);
bool operator != (const Complex& c);
Complex& operator = (const Complex& c);
complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
private:
int a;
int b;
public:
Complex(double a=0, double b=0);
double GetA();
double GetB();
double GetModulus();
Complex operator + (const Complex& p);
Complex operator - (const Complex& p);
Complex operator * (const Complex& p);
Complex operator / (const Complex& p);
bool operator == (const Complex& p);
bool operator != (const Complex& p);
Complex& operator = (const Complex& p);
};
#endif // COMPLEX_H
complex.cpp
#include "complex.h"
#include "math.h"
Complex::Complex(double a, double b)
{
this->a = a;
this->b = b;
}
double Complex::GetA()
{
return a;
}
double Complex::GetB()
{
return b;
}
double Complex::GetModulus()
{
return sqrt(a * a + b * b);
}
Complex Complex::operator +(const Complex& p)
{
double na = a + p.a;
double nb = b + p.b;
Complex ret(na,nb);
return ret;
}
Complex Complex::operator -(const Complex& p)
{
double na = a - p.a;
double nb = b - p.b;
Complex ret(na,nb);
return ret;
}
Complex Complex::operator *(const Complex& p)
{
// c1 = a + bi
// c2 = c + di
// c1 * c2 = (a*c -b*d) +(b*c+ a*d)
double na = (a * p.a) - (b * p.b);
double nb = (b * p.a) + (a * p.b);
Complex ret(na,nb);
return ret;
}
Complex Complex::operator /(const Complex& p)
{
double cm = p.a * p.a + p.b * p.b;
double na = (a * p.a + b * p.b) / cm;
double nb = (b * p.a - a * p.b) / cm;
Complex ret(na,nb);
return ret;
}
bool Complex::operator ==(const Complex& p)
{
return (a == p.a) && (b == p.b);
}
bool Complex::operator !=(const Complex& p)
{
return !(*this == p);
}
Complex& Complex::operator =(const Complex& p)
{
if(this != &p)
{
a = p.a;
b = p.b;
}
return *this;
}
main.cpp
#include <stdio.h>
#include "complex.h"
int main()
{
Complex c1(1,2);
Complex c2(3,6);
Complex c3 = c2 - c1;
Complex c4 = c1 * c3;
Complex c5 = c2 / c1;
printf("c3.a = %f,c3.b = %f\n",c3.GetA(),c3.GetB());
printf("c4.a = %f,c4.b = %f\n",c4.GetA(),c4.GetB());
printf("c5.a = %f,c5.b = %f\n",c5.GetA(),c5.GetB());
Complex c6(2,4);
printf("c3 == c6: %d\n",c3 == c6);
printf("c3 != c4: %d\n",c3 != c4);
(c3 = c2) = c1;
printf("c3.a = %f,c3.b = %f\n",c3.GetA(),c3.GetB());
printf("c2.a = %f,c2.b = %f\n",c2.GetA(),c2.GetB());
printf("c1.a = %f,c1.b = %f\n",c1.GetA(),c1.GetB());
return 0;
}
注意事项:
C++规定赋值操作符(=)只能重载为成员函数
操作符重载不能改变原操作符的优先级
操作符重载不能改变操作数的个数
操作符重载不应改变操作符原有语义
小结:
复数的概念可以通过自定义类实现
复数中的运算操作可以通过操作符重载实现
赋值操作符只能通过成员函数实现
操作符重载的本质为函数定义
原文:https://www.cnblogs.com/-glb/p/11901951.html