31课.完善的复数类
利用操作符重载的练习
注意事项:
1.赋值操作符(=)只能重载为成员函数
2.操作符重载不能改变原操作符的优先级(+, -, *, /)
3.操作符重载不能改变操作符的个数
4.操作符重载不应改变操作符的原有语义(3,4说明操作符重载只是对原有操作符功能的扩展,但是不能改变其本质的含义。比如:+只能是二目运算符的加法。不能是三目,也不能是减法)
练习:完善复数符+,-,*,/,==,!,=;
头文件:
#ifndef _COMPLEX_H_
#define _COMPLEX_H_
class Complex
{
double a;
double b;
public:
Complex(double a = 0, double b = 0);
double getA();
double getB();
double getModulus();
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);
};
#endif
.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& c)
{
double na = a + c.a; //成员函数可以直接使用成员变量
double nb = b + c.b;
Complex ret(na, nb);
return ret;
}
Complex Complex::operator - (const Complex& c)
{
double na = a - c.a;
double nb = b - c.b;
Complex ret(na, nb);
return ret;
}
Complex Complex::operator * (const Complex& c)
{
double na = a * c.a - b * c.b;
double nb = a * c.b + b * c.a;
Complex ret(na, nb);
return ret;
}
Complex Complex::operator / (const Complex& c)
{
double cm = c.a * c.a + c.b * c.b;
double na = (a * c.a + b * c.b) / cm;
double nb = (b * c.a - a * c.b) / cm;
Complex ret(na, nb);
return ret;
}
bool Complex::operator == (const Complex& c)
{
return (a == c.a) && (b == c.b);
}
bool Complex::operator != (const Complex& c)
{
return !(*this == c); //这里引用了上面的==
}
Complex& Complex::operator = (const Complex& c)
{
if( this != &c ) //如果左右操作数不是同一个对象,再进行赋值
{
a = c.a;
b = c.b;
}
return *this; //赋值操作是可以是连续的返回(对象的引用),并且赋值操作返回值为做操作数(返回*this)。
}