C++ 中 operator() 重載與最佳實踐
更新時間:2026年01月07日 10:10:52 作者:會飛的胖達(dá)喵
本文詳細(xì)介紹了C++中operator()重載的概念和應(yīng)用,包括函數(shù)對象的定義、狀態(tài)保持、比較器、算法庫中的應(yīng)用、函數(shù)對象容器、高級應(yīng)用場景以及性能考慮與最佳實踐,感興趣的朋友跟隨小編一起看看吧
C++ 中 operator() 重載詳解
1. operator() 重載基礎(chǔ)概念
1.1 函數(shù)對象定義
- 函數(shù)對象(Functor):重載了 operator()的類實例,可以像函數(shù)一樣被調(diào)用
- 語法格式:
ReturnType operator()(ParameterList) const - 靈活性:支持多種參數(shù)列表的重載版本
1.2 基礎(chǔ)示例
class Adder {
public:
int operator()(int a, int b) const {
return a + b;
}
};
// 調(diào)用示例
Adder adder;
int result = adder(5, 3); // 等價于 adder.operator()(5, 3)2. 狀態(tài)保持的函數(shù)對象
2.1 計數(shù)器實現(xiàn)
class Counter {
private:
int count;
int step;
public:
Counter(int initial = 0, int increment = 1) : count(initial), step(increment) {}
// 無參數(shù)調(diào)用,返回當(dāng)前值并遞增
int operator()() {
int current = count;
count += step;
return current;
}
// 重置計數(shù)器
void operator()(int value) {
count = value;
}
// 重載帶步長的調(diào)用
int operator()(int start, int increment) {
count = start;
step = increment;
return operator()(); // 調(diào)用無參版本
}
};
// 調(diào)用示例
Counter counter(0, 1);
int val1 = counter(); // 返回 0,count 變?yōu)?1
int val2 = counter(); // 返回 1,count 變?yōu)?2
counter(10); // 重置為 10
int val3 = counter(100, 5); // 重置為 100,步長為5,返回1002.2 累加器實現(xiàn)
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;
}
};
// 調(diào)用示例
Accumulator acc(0);
int result1 = acc(5); // sum = 5
int result2 = acc(3); // sum = 8
acc(10, true); // 重置后累加,sum = 103. 比較器函數(shù)對象
3.1 字符串長度比較器
class StringLengthComparator {
public:
bool operator()(const std::string& a, const std::string& b) const {
return a.length() < b.length();
}
};
// 調(diào)用示例
std::vector<std::string> strings = {"apple", "banana", "cherry", "date"};
std::sort(strings.begin(), strings.end(), StringLengthComparator());3.2 數(shù)值比較器
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;
}
};
// 調(diào)用示例
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. 算法庫中的應(yīng)用
4.1 自定義謂詞函數(shù)對象
class GreaterThan {
private:
int threshold;
public:
GreaterThan(int t) : threshold(t) {}
bool operator()(int value) const {
return value > threshold;
}
};
// 調(diào)用示例
std::vector<int> numbers = {1, 5, 3, 8, 2, 9};
int count = std::count_if(numbers.begin(), numbers.end(), GreaterThan(5));
// count = 2 (8, 9)4.2 變換函數(shù)對象
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;
}
};
// 調(diào)用示例
std::vector<int> input = {1, 2, 3, 4, 5};
std::vector<int> output(input.size());
// 使用 Square
std::transform(input.begin(), input.end(), output.begin(), Square());
// output = {1, 4, 9, 16, 25}
// 使用 AddConstant
std::transform(input.begin(), input.end(), output.begin(), AddConstant(10));
// output = {11, 12, 13, 14, 15}5. 函數(shù)對象容器
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;
}
};
// 調(diào)用示例
OperationContainer addOp("add");
OperationContainer mulOp("mul");
int result1 = addOp(5, 3); // 返回 8
int result2 = mulOp(5, 3); // 返回 155.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;
}
};
// 調(diào)用示例
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 過濾偶數(shù)
Filter evenFilter([](int x) { return x % 2 == 0; });
auto evenNumbers = evenFilter(numbers); // {2, 4, 6, 8, 10}
// 過濾大于5的數(shù)
Filter greaterFilter([](int x) { return x > 5; });
auto greaterNumbers = greaterFilter(numbers); // {6, 7, 8, 9, 10}6. 高級應(yīng)用場景
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;
}
};
// 調(diào)用示例
Closure closure(10);
int result1 = closure(5); // 返回 15 (5 + 10)
int result2 = closure(3, 4); // 返回 22 (3 * 4 + 10)6.2 函數(shù)組合器
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));
}
};
// 調(diào)用示例
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); // 先執(zhí)行 increment(5) = 6, 再執(zhí)行 square(6) = 367. 性能考慮與最佳實踐
7.1 const 修飾符使用
class StatelessFunction {
public:
// 無狀態(tài)函數(shù)對象應(yīng)使用 const 修飾
int operator()(int x) const {
return x * 2;
}
};7.2 引用參數(shù)傳遞
class StringProcessor {
public:
std::string operator()(const std::string& input) const {
// 使用 const 引用避免拷貝
return input + "_processed";
}
};8. 總結(jié)
- 靈活性:operator()重載提供了函數(shù)對象的靈活性
- 狀態(tài)保持:函數(shù)對象可以維護(hù)內(nèi)部狀態(tài)
- 算法兼容:與 STL 算法完美配合
- 性能優(yōu)勢:編譯時優(yōu)化,避免函數(shù)指針調(diào)用開銷
- 類型安全:編譯時類型檢查,避免運(yùn)行時錯誤
到此這篇關(guān)于C++ 中 operator() 重載詳解的文章就介紹到這了,更多相關(guān)C++ operator() 重載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言中多維數(shù)組的內(nèi)存分配和釋放(malloc與free)的方法
寫代碼的時候會碰到多維數(shù)組的內(nèi)存分配和釋放問題,在分配和釋放過程中很容易出現(xiàn)錯誤。下面貼上一些示例代碼,以供參考。2013-05-05
關(guān)于C/C++中typedef的定義與用法總結(jié)
在C還是C++代碼中,typedef都使用的很多,在C代碼中尤其是多,typedef與#define有些相似,其實是不同的,特別是在一些復(fù)雜的用法上,需要的朋友可以參考下2012-12-12
C/C++計算程序執(zhí)行時間的幾種方法實現(xiàn)
本文主要介紹了C/C++計算程序執(zhí)行時間的幾種方法實現(xiàn),包括使用clock()函數(shù)、使用庫和使用time.h頭文件中的time()函數(shù),具有一定的參考價值,感興趣的可以了解一下2025-02-02

