操作符重载,成员函数this
1、操作符作用于左边,左边作为this被编译器传入函数
complex c1(5);
complex c2(1,2);
c2 += c1;
inline complex& _doapl(complex* ths, const complex& r)//时刻注意传入不改变值的参数加const
{
this->re += r.re;
this->im += r.im;
return *this;
}
//操作符重载
inline complex& complex::operator += (const complex& r)//实际上inline complex& complex::operator += (this, const complex& r)
{
return _doapl(this, r);
}
//注意:1、inline建议使用2、const修饰只读参数3、类的成员函数定义加classname::4、谁调用重载操作符谁就是this5、引用即对象本身,不是指向对象的指针,但是传递引用即传递对象的地址
2、return by reference语法分析
??并没有特别透彻的理解:传递者无需知道接收者以reference形式接收
接收者可以按值接收也可以按引用接收,而传递者无需知道这一点
//返回值接收例子
inline complex& _doapl(complex* ths, const complex& r)//返回值complex&接收者
{
this->re += r.re;
this->im += r.im;
return *this;//传递者
}
//参数接收例子
inline complex& complex::operator += (const complex& r)//参数complex&接收者,可以作为值value接受也可以作为引用接收
{
return _doapl(this, r);
}
complex c1(5);
complex c2(1,2);
c2 += c1;//传递者c1作为参数传递
3、运算符重载设计思想
c1 += c2;不需要return,可以返回void,只需要把+的操作执行完即可,但是
c1 += c2 +=c3;这就需要+=有返回值。所以需要设计重载时返回一个对象。
操作符重载,非成员函数 无this
1、这些函数不能return by reference
complex c1(5);
complex c2(2,3);
complex c2 = c1 + c2;
//非成员函数的运算符重载声明
inline complex operator + (const complex& c1, const complex& c2)//不能返回引用,因为该函数非类的成员函数,没有this指针,相加的结果的声明周期在函数结束后就消亡了。如果返回引用则把死的东西引用给别人。
{
// return complex(c1.re + c2.re, c1.im + c2.im);错误,不能直接取用c1\c2的private
return complex(real(c1) + real(c2), imag(c1) + imag(c2));//结果存放在函数里面创建的临时对象
}
2、临时对象到下一行声明就结束
函数创建的临时对象绝对不能return by reference 必须return by value,例子见第1点
complex c1();
complex c2(2,3);//这俩有名字
complex();
complex(4,5);//这俩没有名字,声明到下一行就结束
cout << complex(3);
3、<<操作符重载
//输出复数
complex c1(1,2);
cout << c1 ;//输出(1,2)
//为了实现输出复数,需要重载操作符<<
#include<iostream.h>
void operator << (ostream os, complex c)
{
cout << '(' << real(c) << ',' << imag(c) << ')';
}
/*1.complex c未改变 需加上const
2.参数按引用传递,效率更高
3.考虑cout << c1 << c2的情况,需要返回ostream.c1抛给cout,然后c2再抛给cout,所以c1抛完之后必须返回一个cout*/
//函数改进为
ostream& operator << (ostream& os, const complex& c)//os是系统存在的,不是临时变量,可以传引用
{
return os << '(' << real(c) << ',' << imag(c) << ')';
}