1. 匿名对象
1.1语法
类名()
1.2代码
#include<iostream>
#include<string>
using namespace std;
//输出类
class Myprint
{
public:
//重载函数调用运算符
void operator()(string text)
{
cout << text << endl;
}
};
void test1()
{
Myprint myPrint;
myPrint("Hello World");//由于使用起来非常类似于函数调用,因此称为仿函数
}
//加法类
class MyAdd
{
public:
int operator()(int a, int b)
{
return a + b;
}
};
void test2()
{
//MyAdd myadd;
//cout<<myadd(10, 20) << endl;//30
//匿名函数的对象//MyAdd()创建了匿名对象,然后再调用重载运算符(10,20)
cout << MyAdd()(10, 20) << endl;//30
}
int main()
{
test1();//Hello World
test2();//30
system("pause");
return 0;
}