1 函数参数对象值传递:
#include<iostream>
using namespace std;
class Demo
{
public:
int x;
Demo(int x)
{
this->x = x;
}
};
Demo operator+(Demo a,Demo b)
{
cout << "operator内a、b地址:" << &a << " " << &b << endl;
Demo c(a.x + b.x);
cout << "operator内c地址:" << &c << endl;
return c;
}
int main()
{
Demo a(1), b(2);
cout << "main内a、b地址:" << &a << " " << &b << endl;
cout << "main内c地址:" << &(a+b) << endl;
system("pause");
return 0;
}
可见对象传递过去会被拷贝。
2 函数参数对象引用传递
修改+号重载函数:
Demo operator+(Demo &a,Demo &b)
{
cout << "operator内a、b地址:" << &a << " " << &b << endl;
Demo c(a.x + b.x);
cout << "operator内c地址:" << &c << endl;
return c;
}
可见函数参数引用传递不需要拷贝新对象。
3 返回对象值
从上面结果可以看出,是拷贝,因为局部变量c出了函数域就会被销毁,因此在函数域外是函数域内的c的拷贝。
4 返回对象的引用
修改+号重载函数为:
Demo& operator+(Demo &a,Demo &b)
{
cout << "operator内a、b地址:" << &a << " " << &b << endl;
Demo c(a.x + b.x);
cout << "operator内c地址:" << &c << endl;
return c;
}
可以看出在+号重载函数与调用函数main内两个的c是同一个地址的,但是问题是回到main函数时,该地址的内存已经被销毁了,将main函数改为下面的形式进行验证:
int main()
{
Demo a(1), b(2);
cout << "main内a、b地址:" << &a << " " << &b << endl;
Demo& c = a + b;
cout << "main内c地址:" << &c << " 值:" << c.x << endl;
system("pause");
return 0;
}
结果可见,该内存并没有被销毁,不知道是不是VS的返回值优化“return value optimization"在起作用。
5 const作用
理想的重载函数应该为:
const Demo operator+(const Demo &a,const Demo &b)
{
return Demo(a.x + b.x);//不出现局部/临时变量名c,给予编译器最大权限去优化
}
第一个const修饰函数是为了防止不符合使用习惯的下式出现:
( a + b) = c;
如果没有const修饰函数,a+b会返回一个Demo的临时/局部变量,可以再被c赋值,但是这不符合我们的使用习惯,而且给一个临时/局部变量赋值一般情况下也没有意义。
后面参数的两个const是为了防止调用函数改变引用的变量,即给予引用变量a、b只读属性。