操作符重载分为成员操作符重载(number function)和非成员操作符重载(non-number functon),并不是所有的操作符都可以进行非成员函数操作符重载的,具体可以参考官网:http://www.cplusplus.com/doc/tutorial/templates/
先上代码:
#include <iostream>
using namespace std;
class complex
{
private:
int re;
int im;
public:
complex(int r ,int i ); //错误写法, complex(int r = 0,int i = 0 );
~complex();
inline int real() const { return re;} //内联函数
inline int imag() const { return im;}
complex operator+ (complex &n);
};
complex::complex(int r = 0 ,int i = 0 )
: re (r),im (i) //构造函数的初始化列表
{
//re = r;
//im = i;
}
complex::~complex()
{
}
complex complex::operator+ (complex &n)
{
return complex (this->real() + n.real(),this->imag() + n.imag());
}
ostream & operator<<(ostream &os,complex &n)//操作符重载
{
os << n.real() << "+" << n.imag() << "i";
return os;
}
main()
{
complex a(4,5);
complex b(1,1);
complex c = a+b;
cout << c << endl;
return 0;
}
接着上一篇博客,今天讨论的问题是,成员函数的重载:
complex complex::operator+ (complex &n)//成员函数的重载
{
return complex (this->real() + n.real(),this->imag() + n.imag());
}
ostream & operator<<(ostream &os,complex &n)//非成员函数的重载
{
os << n.real() << "+" << n.imag() << "i";
return os;
}
上个博客说过,成员函数的操作符重载就好比是一个函数,造作符左右两个变量,分别对应函数的第一个和第二个形参,这样是很容易理解的。但是成员函数的操作符重载函数只有一个参数,这就十分奇怪啦。其实编译器在编译到成员函数的时候,会做如下操作:
class a;
class b;
class c;
c = a + b;//编译前
// c = a.operator+b;//编译后
这样就容易理解多了,基于这种原因,成员函数操作符重载的写法有很多种,如下:
complex complex::operator+ (complex &n)
{
return complex (this->real() + n.real(),this->imag() + n.imag());
}
complex complex::operator+ (complex &n)
{
return complex (real() + n.real(),imag() + n.imag());
}
complex complex::operator+ (complex &n)
{
return complex (re + n.re,im + n.im);
}
对上面三段代码进行一下解释:
- complex(),这个是创建了一个临时对象,临时对象没有名字,用来传值之后就会死亡。因此这里的函数返回用的是传值,而非传引用。
- n.re,第三种我写了这种形式,对于private中的成员变量来说,我们在正常使用是不能这样写的,但是在定义成员函数就可以这样使用。
- 第一种方法我们引入了this指针,之后我们会再来做探讨。