C++:操作符重载与临时对象

    技术2022-07-11  98

    operator overlording(操作符重载,成员函数)this 实现:c2 += c2;//重载+=, 所有的成员函数都带有一个参数,即this,上面的c2就是*this,也就是传入this = &c2; inline complex& complex::opertaor += (const complex& r) { return __doapl(this,r);//这里的this就是+=左边的部分,并且传入另一个函数中 } inline complex& __doapl (const complex& ths,complex& r)//将上面的this传入ths { ths->re += r.re; ths -> im +=r.im; return *ths; }

    1、return by reference语法分析 传递者无需知道接收者是以reference形式接收。 2、class body之外的各种定义(definitions) temp object(形式对象) inline complex operator + (const complex& x,const complex& y) { return complex(real(x)+real(y),imag(x)+imag(y)); } 这个成员函数决不可return by reference ,因为他们返回的是个local object,在程序结束的时候,就消失了。而且没有名称,所以绝对不能返回引用。所以要改为return by value. 小结:尽量不要创建临时对象,所以最好用变量创建一个对象。
    Processed: 0.015, SQL: 9