5.操作符重载与临时对象
1.操作符重载1,成员函数,有this

2.操作符重载2,非成员函数,无this
/* 重载复数的算术运算符和关系运算符 /
/ 下面这些函数绝不可return by reference
因为他们返回的必定是个local object */
inline complex
operator + (const complex& x, const complex& y)
{
return complex(real(x) + real(y), imag(x) + imag(y));
}
inline complex
operator + (const complex& x, double y)
{
return complex(real(x) + y, imag(x));
}
inline complex
operator + (double x, const complex& y)
{
return complex(x + real(y), imag(y));
}
complex c1(2,1);
complex c2;
c2 = c1 + c2;
c2 = c1 + 5;
c2 = 5 + c1;
编译器会找符合条件的+
3.临时对象

问题1:为什么返回值类型是complex对象的引用,而代码里的返回值是指针解引用
inline complex& //接收端
__doapl (complex* ths, const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return ths;
}
答:complex ths:是一个指针,指向某个 complex 对象
*ths:对指针解引用,得到指针指向的那个对象本身
complex&:是对某个 complex 对象的引用
对一个对象的引用,和对指向这个对象的指针解引用,结果是完全等价的!
问题2:为什么可以写成cout<<c1的形式,而不是operator <<(cout,c1)
include <iostream.h>
ostream& operator << (ostream& os, const complex& x)
{
return os << '(' << real (x) << ','
<< imag (x) << ')';
}
{
complex c1(2,1);
cout << conj(c1);
cout << c1 << conj(c1);
}
答:首先,两种写法在语义上是完全等价的
定义的时候只能写函数形式,这是语言规则;但使用的时候既可以用函数形式,也可以用运算符形式,这是语法糖。
运算符重载只能通过函数来定义,不能直接定义新的语法规则
比如:
1.内置类型
int a = 1, b = 2;
int c = a + b; // 永远是 3
2.自定义类型(你只能改“行为”)
struct Vec2 {
int x, y;
};
Vec2 operator+(const Vec2& a, const Vec2& b)
{
return {a.x + b.x, a.y + b.y};
}
你没有改变 + 的用法,你只是告诉编译器:当 + 作用在 Vec2 上时,请这样算
Vec2 v1{1,2}, v2{3,4};
Vec2 v3 = v1 + v2; // 仍然是 v1 + v2

浙公网安备 33010602011771号