#include <iostream>
#include <string>
using namespace std;
class MyPrint{
public:
    // 重载小括号() 重载谁operator后就紧跟谁的符号
    void operator()(string txt){
        cout << txt << endl;
    }
};
class MyAdd{
public:
    int operator()(int a, int b){
        return a + b;
    }
};
void my_print(string str){
    cout << str << endl;
}
int main()
{
    my_print("哈哈"); // 普通函数写法
    
    MyPrint my;
    my("呵呵");  // 仿函数:本质就一个函数对象 
    MyAdd ma;
    cout << ma(1, 2)<< endl;  // 遇到()程序不知道在干啥,就会往上找到  int operator()(int a, int b)
    // 类名()  这种写法叫匿名对象  当前执行完毕后,立即释放内存空间
    // MyAdd()(2, 3) 匿名函数对象 当前执行完毕后,立即释放内存空间
    cout << MyAdd()(2,3) << endl; 
    
    return 0;
}
 

不要重载&&、||
不能重载operator&& 和 operator|| 的原因是,无法在这两种情况下实现内置操作符的完整语义(短路规则)。说得更具体一些,内置版本版本特殊之处在于:内置版本的&&和||首先计算左边的表达式,如果这完全能够决定结果,就无需计算右边的表达式了--而且能够保证不需要。我们都已经习惯这种方便的特性了。
我们说操作符重载其实是另一种形式的函数调用而已,对于函数调用总是在函数执行之前对所有参数进行求值。

![[大模型]XVERSE-7B-chat langchain 接入](https://img-blog.csdnimg.cn/direct/449c21e11ca6407595ccc83d31000e7d.png#pic_center)
















