函数调用符()重载及总结

函数调用符()重载

为了优化类成员函数的调用,对函数调用符()进行重载

#include <iostream>

using namespace std;
class Fun
{
public:
    int my_add(int x,int y)
    {
        return x+y;
    }
    //重载()
    //第一个()是重载的符号 第二个()是标明要传参
    int operator()(int x,int y)
    {
        return x+y;
    }
};

void test01()
{
    Fun fun;
    cout<<fun.my_add(100,200)<<endl;

    cout<<fun.operator ()(100,200)<<endl;
    //优化 fun和()结合 就会自动寻找()运算符
    cout<<fun(100,200)<<endl;
    //此处 fun(100,200)不是一个真正的函数 仅仅是一个对象名和()结合 调用()重载运算符而已
    //fun不是函数名 只是fun(100,200)类似一个函数调用 所以将fun(100,200)叫做仿函数

    //此处的Fun是类名称
    //Fun()匿名对象 Fun()(100,200) 就是匿名对象(100,200)
    cout<<Fun()(100,200)<<endl;//了解

}
int main(int argc, char *argv[])
{
    test01();
    return 0;
}

不要重载&&、||

因为用户无法实现 && ||的短路特性。
&& 短路特性: A && B 如果A为假 B将不会执行
|| 短路特性: A || B 如果A为真 B将不会执行

#include <iostream>

using namespace std;

class Complex{
public:
    Complex(int flag){
        this->flag = flag;
    }
    Complex& operator+=(Complex& complex){
        this->flag = this->flag + complex.flag;
        return *this;
    }
    bool operator&&(Complex& complex){
        return this->flag && complex.flag;
    }
public:
    int flag;
};
int main(){

    Complex complex1(0);  //flag 0
    Complex complex2(1);  //flag 1

    //原来情况,应该从左往右运算,左边为假,则退出运算,结果为假
    //这边却是,先运算(complex1+complex2),导致,complex1的flag变为complex1+complex2的值, complex1.a = 1
    // 1 && 1
    //complex1.operator&&(complex1.operator+=(complex2))
    if (complex1 && (complex1 += complex2)){
        //complex1.operator+=(complex2)
        cout << "真!" << endl;
    }
    else{
        cout << "假!" << endl;
    }

    return EXIT_SUCCESS;
}

符号重载的总结

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值