一、运算符重载
格式:[返回值类型] operator[被重载运算符](同返回值类型& [形参]){}
- Complex c(1,2);
- Complex c2(3,4);
- c.Plus(c2);
- c+c2;
- 注:对于本节调用函数时,this指向的是c,函数中real是c的,c.real是c2的
- 谁在前谁就是this所指向的,在后就是c形参;
#include <iostream>
#include <cmath>
using namespace std;
/*
* @brief 复数
*/
class Complex{
private:
// 成员变量
float real;// 实部
float imag;// 虚部
public:
Complex(float r = 0,float i = 0){
Init(r,i);
}
// 成员函数
// 初始化
void Init(float r,float i){
real = r;
imag = i;
}
// 加
Complex Plus(Complex c){
Complex res;
// 在类内部,可以直接访问本类的其他对象的所有成员.
res.real = real + c.real;
res.imag = imag + c.imag;
return res;
}
Complex operator+(const Complex& c)const{
Complex res;
res.real = real + c.real;
res.imag = imag + c.imag;
return res;
}
Complex Plus(const Complex* p){
Complex res;
res.real = real + p->real;
res.imag = imag + p->imag;
return res;
}
// 减
Complex Divide(Complex c){
Complex res;
// 在类内部,可以直接访问本类的其他对象的所有成员.
res.real = real - c.real;
res.imag = imag - c.imag;
return res;
}
Complex operator-(const Complex& c)const{
Complex res;
// 在类内部,可以直接访问本类的其他对象的所有成员.
res.real = real - c.real;
res.imag = imag - c.imag;
return res;
}
Complex operator-()const{
Complex res;
res.real = -real;
res.imag = -imag;
return res;
}
Complex operator+()const{
return *this;
}
// 乘
// 除
// 取模
float Mode(){
return sqrt(real*real+imag*imag);
}
// 相等
bool Equal(Complex c){
return real == c.real && imag == c.imag;
}
bool operator==(const Complex & c) const{
return real == c.real && imag == c.imag;
}
// 不相等
bool NotEqual(Complex c){
return !Equal(c);
}
bool operator!=(const Complex& c) const{
return !(*this == c);
}
// 打印
void Print(){
cout << real;
if(imag > 0){
cout<< "+";
}
cout << imag << "i" << endl;
}
friend ostream& operator<<(ostream& os,const Complex& c);
};
ostream& operator<<(ostream& os,const Complex& c){
os << c.real;
if(c.imag > 0){
os<< "+";
}
os << c.imag<< "i" << endl;
// return os;
}
int main(){
Complex c(3,4);
// Complex c;// 报错
// c.Init(3,4);
c.Print();
cout << c << endl;
Complex c1;
c1.Init(5,9);
c1.Print();
Complex res = c.Divide(c1);
res.Print();
Complex res1 = c1.Divide(c);
res1.Print();
cout << c.Equal(c1) << endl;
cout << c.Equal(c) << endl;
// c + c1 - c
c.Plus(&c1).Divide(c).Print();
c.operator+(c1).operator-(c).Print();
(c+c1-c).Print();
cout << (c==c1) << endl;
cout << (c1==c1) << endl;
const Complex c2(3,4);
cout << (c2 == c) << endl;
// (-c2).Print();
cout << (-c2) <<endl;
(cout << (-c2)) << endl;
}