类和对象–C++运算符重载
C++ 预定义的运算符,只能用于基本数据类型的运算,不能用于对象的运算
如何使运算符能用于对象之间的运算呢
函数调用运算符重载
函数调用运算符 () 的重载
由于重载后使用的方式非常像函数的调用,因此称为仿函数,仿函数在STL中用得比较多
自定义打印函数
#include <iostream>
using namespace std;
#include <string>
class MyPrint{
public:
void operator()(string myprint){
cout << myprint << endl;
}
};
void test(){
MyPrint myprint;//实例化一个对象
myprint("hello world");
}
int main(){
test();
system("pause");
return 0;
}
运行结果:
将实例化对象的参数传到仿函数内
自定义加法函数
#include <iostream>
using namespace std;
class MyAdd{
public:
int operator()(int num1, int num2){
return num1 + num2;
}
};
void test(){
MyAdd add;
int ret = add(10, 10);
cout << "ret = " << ret << endl;
//匿名对象调用
cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}
int main(){
test();
system("pause");
return 0;
}
运行结果:
将实例化对象的参数传到仿函数内
因为仿函数既可以是int 又可以是void,还可以是其他的,即 仿函数没有固定写法,非常灵活