void operator()()的功能


在學習多線程的時候看到這樣的一段代碼,為什么要重載()呢?真有這個必要嗎?

#include <iostream>
#include <thread>

class Counter {
public:
  Counter(int value) : value_(value) {
  }

  void operator()() {
    while (value_ > 0) {
      std::cout << value_ << " ";
      --value_;
      std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    std::cout << std::endl;
  }

private:
  int value_;
};

int main() {
  std::thread t1(Counter(3));
  t1.join();

  std::thread t2(Counter(3));
  t2.detach();

  // 等待幾秒,不然 t2 根本沒機會執行。
  std::this_thread::sleep_for(std::chrono::seconds(4));
  
  return 0;
}

對 void operator()()的功能表示困惑

// 查閱了一些資料,這個是簡易的說明代碼
class background_task
{
public:
    void operator()() const
    {
        do_something();
        do_something_else();
    }
};
background_task f;
std::thread my_thread(f);

在這里,為什么我們需要operator()()?第一個和第二個()的意思是什么?其實我知道這是重載運算符的操作()

我們在學習C++的時候,學習過運算符重載。這里重載() 可以使對象像函數那樣使用,常常被稱為函數對象。 (這里用作線程對象的構造)

第一個()是運算符的名稱 – 它是在對象上使用()時調用的運算符. 第二個()是用於參數的。
以下是您如何使用它的示例:

background_task task;
task();  // calls background_task::operator()

有參數的演示:

#include <iostream>

class Test {
public:
    void operator()(int a, int b) {
        std::cout << a + b << std::endl;
    }
};

int main() {
    Test t;
    t(3,5);
    return 0;
}

// 輸出結果
// 8


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM