前言
运算符重载是C++的一种非常方便(重要)的方法(考点)。
本文以Complex(复数)类为例子,简单解释这两种重载方式。
class Complex
{
double real;//实部
double im;//虚部
public:
//成员函数
Complex(double r,double i):re(r),im(i){};//构造函数
...
}
成员函数重载
以加法为例:
Complex operator +(Complex z1)
{
Complex z(0,0);
z.re = z1.re+this->re;
z.im = z1.im+this->im;
return z;
}
以减法为例:
Complex operator -(Complex z1)
{
Complex z(0,0);
z.re = this->re-z1.re;
z.im = this->im-z1.im;
return z;
}
友元函数重载
重载为友元函数时,友元函数内部没有this指针的概念
以加法为例:
friend Complex operator(Complex z1,Complex z2)
{
Complex z(0,0);
z.re = z1.re+z2.re;
z.im = z1.im+z2.im;
return z;
}
以减法为例
friend Complex operator (Complex z1,Complex z2)
{
Complex z(0,0);
z.re = z1.re - z2.re;
z.im = z1.im - z2.im;
return z;
}
总结
虽然说运算符一般情况下都可以以这两种方式进行重载,但又有约定俗成的规矩。
- 单目运算符一般采用成员函数重载方式重载。
- 双目运算符一般采用友元函数重载方式重载
另外一些特定的运算符只能采用特定的方式重载。
- =,(),[],->双目运算符不能重载为类的友元函数
- ">>"和“<<”只能重载为类的友元函数
可执行程序源代码
#include <iostream>
using namespace std;
class Complex
{
private:
double re,im;
public:
Complex(double r,double i):re(r),im(i){};
double real()
{
return re;
}
double imag()
{
return im;
}
Complex operator +(Complex z1)//可以定义为友元函数,也可以定义为成员函数
{
Complex z(0,0);
z.re = z1.re+this->re;
z.im = z1.im+this->im;
return z;
}
//friend Complex operator +(Complex z1,Complex z2)
Complex operator -(Complex z1)//可以定义为友元函数,也可以定义为成员函数
{
Complex z(0,0);
z.re = this->re-z1.re;
z.im = this->im-z1.im;
return z;
}
//friend Complex operator +(Complex z1,Complex z2)
Complex operator -()
{
Complex z(-this->re,-this->im);
return z;
}
Complex operator +()
{
return *this;
}
Complex& operator += (Complex z)//含有赋值操作,用&
{
re+=z.re;
im+=z.im;
return *this;
}
Complex& operator += (double z)
{
re+=z;
return *this;
}
void print()
{
cout<<"real:"<<re<<" "<<"imag:"<<im<<endl;
}
friend Complex operator *(Complex c1, Complex c2)
{
Complex c(0,0);
c.re = c1.re*c2.re-(c1.im*c2.im);
c.im = c1.re*c2.im+c1.im*c2.re;
return c;
}
Complex operator /(Complex c)
{
Complex c0(c.re,-c.im);
Complex c1(0,0);
c1 = c0*c;//c1.re为分母;
*this = (*this)*c0;
this->re/=c1.re;
this->im/=c1.re;
return *this;
}
~Complex(){};
};
int main()
{
Complex c1(2.0,4.0),c2(1.0,3.0),c3(0,0);
c1 = -c2;
c1.print();
c2.print();
c3 = c1+c2;
c3.print();
c3 = c1-c2;
c3.print();
c3 = c1*c2;
c3.print();
c1.print();
c3 = c1/c2;
c3.print();
return 0;
}