最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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,返回100

2.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 = 10

3. 比較器函數(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);  // 返回 15

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;
    }
};
// 調(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) = 36

7. 性能考慮與最佳實踐

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語言超詳細(xì)解析函數(shù)棧幀

    C語言超詳細(xì)解析函數(shù)棧幀

    在C語言中,每一個正在運(yùn)行的函數(shù)都有一個棧幀與其對應(yīng),棧幀中存儲的是該函數(shù)的返回地址和局部變量。從邏輯上講,棧幀就是一個函數(shù)執(zhí)行的環(huán)境:函數(shù)參數(shù)、函數(shù)的局部變量、函數(shù)執(zhí)行完后返回到哪里等等
    2022-03-03
  • C語言中多維數(shù)組的內(nèi)存分配和釋放(malloc與free)的方法

    C語言中多維數(shù)組的內(nèi)存分配和釋放(malloc與free)的方法

    寫代碼的時候會碰到多維數(shù)組的內(nèi)存分配和釋放問題,在分配和釋放過程中很容易出現(xiàn)錯誤。下面貼上一些示例代碼,以供參考。
    2013-05-05
  • 關(guān)于C/C++中typedef的定義與用法總結(jié)

    關(guān)于C/C++中typedef的定義與用法總結(jié)

    在C還是C++代碼中,typedef都使用的很多,在C代碼中尤其是多,typedef與#define有些相似,其實是不同的,特別是在一些復(fù)雜的用法上,需要的朋友可以參考下
    2012-12-12
  • C++實現(xiàn)HTTP服務(wù)的示例代碼

    C++實現(xiàn)HTTP服務(wù)的示例代碼

    本文主要介紹了C++實現(xiàn)HTTP服務(wù)的示例代碼,C++ HTTP,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-04-04
  • C語言簡明講解單引號與雙引號的使用

    C語言簡明講解單引號與雙引號的使用

    這篇文章主要介紹了在C語言里單引號和雙引號的使用,本文通過實例代碼說明了單引號和雙引號的概念與各自的用法,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2022-04-04
  • C語言對磁盤文件進(jìn)行快速排序簡單實例

    C語言對磁盤文件進(jìn)行快速排序簡單實例

    這篇文章主要介紹了C語言對磁盤文件進(jìn)行快速排序簡單實例的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • C/C++計算程序執(zhí)行時間的幾種方法實現(xiàn)

    C/C++計算程序執(zhí)行時間的幾種方法實現(xiàn)

    本文主要介紹了C/C++計算程序執(zhí)行時間的幾種方法實現(xiàn),包括使用clock()函數(shù)、使用庫和使用time.h頭文件中的time()函數(shù),具有一定的參考價值,感興趣的可以了解一下
    2025-02-02
  • EasyC++單獨(dú)編譯

    EasyC++單獨(dú)編譯

    這篇文章主要介紹了EasyC++單獨(dú)編譯,在上一篇當(dāng)中,我們編寫好了頭文件coordin.h,現(xiàn)在我們要完成它的實現(xiàn)。需要的小伙伴可以先學(xué)習(xí)上一篇內(nèi)容然后一起與小編一起進(jìn)入本篇內(nèi)容一起學(xué)習(xí)吧
    2021-12-12
  • C++ 中Vector常用基本操作

    C++ 中Vector常用基本操作

    標(biāo)準(zhǔn)庫vector類型是C++中使用較多的一種類模板,本文給大家分享C++ 中Vector常用基本操作,感興趣的朋友一起看看吧
    2017-10-10
  • 深入分析Linux下如何對C語言進(jìn)行編程

    深入分析Linux下如何對C語言進(jìn)行編程

    本篇文章介紹了,如何在Linux下對C語言進(jìn)行編程的詳細(xì)概述。需要的朋友參考下
    2013-05-05

最新評論

江口县| 双牌县| 宝清县| 金寨县| 盐城市| 社旗县| 东安县| 普洱| 宁乡县| 长治市| 朝阳区| 清镇市| 镇巴县| 防城港市| 青田县| 丁青县| 泰兴市| 开鲁县| 尉氏县| 呈贡县| 东乡县| 河北省| 英德市| 新巴尔虎右旗| 凤山县| 平罗县| 天台县| 星座| 华宁县| 志丹县| 大埔区| 恩平市| 鱼台县| 武功县| 东方市| 孟连| 嘉义县| 化州市| 大渡口区| 湘乡市| 泊头市|