运算符重载(1)

下面的内容是我自己的理解,如有错误,请留言给我,共同进步。


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值