下面的内容是我自己的理解,如有错误,请留言给我,共同进步。
1、 =,(),[],->这四种运算符必须为成员函数形式,其他运算符可以重载为成员函数或友元函数;
2、重载为友元函数形式,形参即为操作数的引用或拷贝;
3、重载为成员函数式,可省略一个形参,另一形参(如果有的话)为另一对象的引用或拷贝。例外,重载++和--时,需要用哑元形参来指示该运算符是后缀,如A operator++( int ),代表A++,而A operator++( )形参不带哑元,代表前缀++A。
#include <QCoreApplication>
#include <iostream>
class Family
{//++作为后缀的重载测试程序
public:
Family(){;}
Family(int f,int m, int c)
{
age_father = f;
age_mother = m;
age_child = c;
}
// Family operator++( int ) //a++ 成员函数重载后缀++和友元函数重载后缀++,只能使用一种
// {
// // 保存原始值
// Family F(*this);//使用默认的拷贝构造函数拷贝构造一个原始副本
// age_father++;//等价于(this->age_father)++
// age_mother++;
// age_child++;
// return F;// 返回旧的原始值
// }
Family IncAfter()//普通成员函数模拟++后缀
{
Family F(*this);//使用默认的拷贝构造函数浅拷贝构造一个原始副本
age_father++;//等价于(this->age_father)++
age_mother++;
age_child++;
return F;// 返回旧的原始值
}
friend Family operator++(Family &obj,int);
int age_father;
int age_mother;
int age_child;
};
Family operator++(Family &obj, int)//友元函数重载后缀++和成员函数重载后缀++,只能使用一种
{
Family F(obj);
obj.age_father++;//等价于(this->age_father)++
obj.age_mother++;
obj.age_child++;
return F;// 返回旧的原始值
}
int main()
{
Family f1(30,30,1);
Family f2;
f2 = f1++;
printf("f1:%d,%d,%d\n",f1.age_father, f1.age_mother, f1.age_child);
printf("f2:%d,%d,%d\n\n",f2.age_father, f2.age_mother, f2.age_child);
f2 = f1.IncAfter();//成员函数IncAfter的功能和后缀++完全一样
printf("f1:%d,%d,%d\n",f1.age_father, f1.age_mother, f1.age_child);
printf("f2:%d,%d,%d\n",f2.age_father, f2.age_mother, f2.age_child);
return 0;
}
结果如下
从上述程序可以看到,后缀F++的功能本质上和上述IncAfter()函数的功能完全一样,有输入有输出,实际上,其他的运算符重载本质上也是函数,如重载下标运算符[],输入为索引,输出为对象的某个元素的引用;又如大于号>的重载,输入为两个对象的引用或拷贝,输出为true或false
参考:https://www.cnblogs.com/zsq1993/p/6057181.html