1.定义
2.特点
、
1.解释第一句
#include<stdio.h>
using namespace std;
#include<string>
#include<map>
#include <iostream>
class print
{
public:void operator()(string s){cout << s << endl;}
};
int main()
{print print;print("hello world");return 0;
}
2.解释第二句
可以有自己的状态:指的是他和普通的函数不同,例如他可以统计自己调用了几次。
也就是说,它可以向函数一样被调用,但是却拥有类的功能,他是类和函数的结合。
#include<stdio.h>
using namespace std;
#include<string>
#include<map>
#include <iostream>
class print
{
public:print(){this->count = 0;}void operator()(string s){cout << s << endl;this->count++;}int count;
};
int main()
{print print;print("hello world");print("hello world");print("hello world");print("hello world");print("hello world");cout << print.count << endl;return 0;
}
3.解释第三句
#include<stdio.h>
using namespace std;
#include<string>
#include<map>
#include <iostream>
class print
{
public:print(){this->count = 0;}void operator()(string s){cout << s << endl;this->count++;}int count;
};
void test(print p, string s)
{p(s);
}
void test01()
{print print;test(print, "C++");
}
int main()
{test01();return 0;
}
函数对象不仅可以作为函数参数,还可以再调用的函数中去使用自己重载过的小括号
具体见
void test(print p, string s)
{
p(s);
}