跳到主要内容C++ operator() 运算符重载详解 | 极客日志C++算法
C++ operator() 运算符重载详解
综述由AI生成C++ 中 operator() 重载机制,即函数对象(Functor)的使用。内容包括基础语法、状态保持实现(如计数器、累加器)、比较器编写、STL 算法库集成应用(sort、transform 等)以及高级场景(闭包模拟、函数组合)。同时探讨了性能优化实践,如 const 修饰符和引用传递,强调其相比函数指针在类型安全和编译期优化上的优势。
不知所云34 浏览 C++ 中 operator() 重载详解
1. operator() 重载基础概念
1.1 函数对象定义
- 函数对象(Functor):重载了 operator() 的类实例,可以像函数一样被调用
- 语法格式:
ReturnType operator()(ParameterList) const
- 灵活性:支持多种参数列表的重载版本
1.2 基础示例
class Adder {
public:
int operator()(int a, int b) const {
return a + b;
}
};
Adder adder;
int result = adder(5, 3);
2. 状态保持的函数对象
2.1 计数器实现
class Counter {
private:
int count;
int step;
public:
Counter(int initial = 0, int increment = 1) : count(initial), step(increment) {}
int operator()() {
int current = count;
count += step;
return current;
}
{
count = value;
}
{
count = start;
step = increment;
();
}
};
;
val1 = ();
val2 = ();
();
val3 = (, );
void operator()(int value)
int operator()(int start, int increment)
return
operator
Counter counter(0, 1)
int
counter
int
counter
counter
10
int
counter
100
5
2.2 累加器实现
class Accumulator {
private:
int sum;
public:
Accumulator(int initial = 0) : sum(initial) {}
int operator()(int value) {
sum += value;
return sum;
}
void operator()(int value, bool reset) {
if (reset) sum = 0;
sum += value;
}
};
Accumulator acc(0);
int result1 = acc(5);
int result2 = acc(3);
acc(10, true);
3. 比较器函数对象
3.1 字符串长度比较器
class StringLengthComparator {
public:
bool operator()(const std::string& a, const std::string& b) const {
return a.length() < b.length();
}
};
std::vector<std::string> strings = {"apple", "banana", "cherry", "date"};
std::sort(strings.begin(), strings.end(), StringLengthComparator());
3.2 数值比较器
class NumberComparator {
private:
bool ascending;
public:
NumberComparator(bool asc = true) : ascending(asc) {}
bool operator()(int a, int b) const {
return ascending ? a < b : a > b;
}
};
std::vector<int> numbers = {5, 2, 8, 1, 9};
std::sort(numbers.begin(), numbers.end(), NumberComparator(true));
std::sort(numbers.begin(), numbers.end(), NumberComparator(false));
4. 算法库中的应用
4.1 自定义谓词函数对象
class GreaterThan {
private:
int threshold;
public:
GreaterThan(int t) : threshold(t) {}
bool operator()(int value) const {
return value > threshold;
}
};
std::vector<int> numbers = {1, 5, 3, 8, 2, 9};
int count = std::count_if(numbers.begin(), numbers.end(), GreaterThan(5));
4.2 变换函数对象
class Square {
public:
int operator()(int x) const {
return x * x;
}
};
class AddConstant {
private:
int constant;
public:
AddConstant(int c) : constant(c) {}
int operator()(int x) const {
return x + constant;
}
};
std::vector<int> input = {1, 2, 3, 4, 5};
std::vector<int> output(input.size());
std::transform(input.begin(), input.end(), output.begin(), Square());
std::transform(input.begin(), input.end(), output.begin(), AddConstant(10));
5. 函数对象容器
5.1 操作器容器
class OperationContainer {
private:
std::string operation;
public:
OperationContainer(const std::string& op) : operation(op) {}
int operator()(int a, int b) const {
if (operation == "add") return a + b;
if (operation == "sub") return a - b;
if (operation == "mul") return a * b;
if (operation == "div") return b != 0 ? a / b : 0;
return 0;
}
};
OperationContainer addOp("add");
OperationContainer mulOp("mul");
int result1 = addOp(5, 3);
int result2 = mulOp(5, 3);
5.2 条件过滤器
class Filter {
private:
std::function<bool(int)> condition;
public:
Filter(std::function<bool(int)> cond) : condition(cond) {}
std::vector<int> operator()(const std::vector<int>& input) const {
std::vector<int> result;
for (int value : input) {
if (condition(value)) {
result.push_back(value);
}
}
return result;
}
};
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Filter evenFilter([](int x){ return x % 2 == 0; });
auto evenNumbers = evenFilter(numbers);
Filter greaterFilter([](int x){ return x > 5; });
auto greaterNumbers = greaterFilter(numbers);
6. 高级应用场景
6.1 闭包模拟
class Closure {
private:
int capture_value;
public:
Closure(int val) : capture_value(val) {}
int operator()(int x) const {
return x + capture_value;
}
int operator()(int x, int y) const {
return x * y + capture_value;
}
};
Closure closure(10);
int result1 = closure(5);
int result2 = closure(3, 4);
6.2 函数组合器
template<typename F, typename G>
class Compose {
private:
F f;
G g;
public:
Compose(F f_func, G g_func) : f(f_func), g(g_func) {}
template<typename T>
auto operator()(T x) const -> decltype(f(g(x))) {
return f(g(x));
}
};
auto square = [](int x){ return x * x; };
auto increment = [](int x){ return x + 1; };
Compose<decltype(square), decltype(increment)> compose(square, increment);
int result = compose(5);
7. 性能考虑与最佳实践
7.1 const 修饰符使用
class StatelessFunction {
public:
int operator()(int x) const {
return x * 2;
}
};
7.2 引用参数传递
class StringProcessor {
public:
std::string operator()(const std::string& input) const {
return input + "_processed";
}
};
8. 总结
- 灵活性:operator() 重载提供了函数对象的灵活性
- 状态保持:函数对象可以维护内部状态
- 算法兼容:与 STL 算法完美配合
- 性能优势:编译时优化,避免函数指针调用开销
- 类型安全:编译时类型检查,避免运行时错误
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- Gemini 图片去水印
基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown转HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
- HTML转Markdown
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online