doc/docs/CPlusPlus-main/30_C++的函数对象.md
sairate fa9377e4ae docs(book): 添加现代 C++教程及相关代码
- 新增现代 C++ 教程的 Preface 章节,包括英文和中文版本
- 添加 C++ Primer 练习代码
- 新增 Learn C++ 教程的 C++ 开发简介章节
- 添加头文件解析文档
- 更新 mkdocs.yml,包含新教程的目录结构
- 修改项目设置,使用 Python 3.10环境
2025-07-08 09:52:45 +08:00

104 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# C++的函数对象
# 1. 基本概念
① 重载函数调用操作符的类,其对象常称为函数对象。
② 函数对象使用重载的()时,行为类似函数调用,也叫仿函数。
③ 函数对象(仿函数)是一个类,不是一个函数。
# 2. 特点
① 函数对象在使用时,可以像普通函数那样调用,可以有参数。
② 函数对象超出普通函数的概念,函数对象可以有自己的状态。
③ 函数对象可以作为参数传递。
④ 仿函数写法是非常灵活的,可以作为参数进行传递。
```python
#include<iostream>
using namespace std;
class MyAdd
{
public:
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
//1函数对象在使用时可以像普通函数那样调用可以有参数可以有返回值
void test01()
{
MyAdd myAdd;
cout << myAdd(10,10) << endl;
}
//2函数对象超出普通函数的概念函数对象可以有自己的状态
class MyPrint
{
public:
MyPrint()
{
this->count = 0;
}
void operator()(string test)
{
cout << test << endl;
this->count++;
}
int count; //内部自己状态
};
void test02()
{
MyPrint myPrint;
myPrint("hellow world");
myPrint("hellow world");
myPrint("hellow world");
myPrint("hellow world");
cout << "myPrint调用次数为" << myPrint.count << endl;
}
//3函数对象可以作为参数传递
void doPrint(MyPrint &mp, string test)
{
mp(test);
}
void test03()
{
MyPrint myPrint;
doPrint(myPrint,"hellow world");
}
int main()
{
test01();
test02();
test03();
system("pause");
return 0;
}
```
运行结果:
- 20
- hellow world
- hellow world
- hellow world
- hellow world
- myPrint调用次数为4
- hellow world
- 请按任意键继续. . .