首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C++ 區域類別實作閉包

     編輯:關於C語言

雖然經常提到閉包,但我對閉包概念不清晰。隱約感覺如果函式 A 中定義並回傳函式 B,而函式 B 在函式 A 之外仍能正常執行並存取函式 A 中定義的變數,同時函式 A 的變數不被外部存取,就叫閉包——若理解錯誤請當我沒說。

看到有人用 C++11 的 std::bind 實作閉包,其實用 C++03 的兩個特性就能實作:區域類別和靜態區域變數。

靜態區域變數

C++ 允許在函式內部定義靜態區域變數,離開函式時不會被銷毀:

  1. void func() {
  2. static int i = 0;
  3. cout << i++ << endl;
  4. }

多次呼叫 func 會發現輸出值持續遞增。

區域類別

想在函式裡定義區域函式是不可能的,但可以定義區域類別,只能在該函式內使用:

  1. void func() {
  2. class LocalClass {
  3. private:
  4. // 定義私有成員
  5. public:
  6. void run() { /* ... */ }
  7. } obj;
  8. obj.run();
  9. }

若需將區域類別物件回傳到外部,需定義介面接收回傳物件並呼叫其方法;函式內需用 new 產生物件並回傳指標:

  1. class ILocal {
  2. public:
  3. virtual void run() = 0;
  4. };
  5. ILocal* func() {
  6. class LocalClass : public ILocal {
  7. public:
  8. virtual void run() { /* ... */ }
  9. };
  10. return new LocalClass();
  11. }

閉包實作範例

  1. #include
  2. using namespace std;
  3. // 介面法實作
  4. class ITest {
  5. public:
  6. void operator()() { process(); }
  7. protected:
  8. virtual void process() = 0;
  9. };
  10. ITest* test() {
  11. static int count = 0;
  12. class Test : public ITest {
  13. public:
  14. virtual void process() { cout << "Count is " << count++ << endl; }
  15. };
  16. return new Test();
  17. }
  18. // 函式指標法實作
  19. typedef void (*Func)(const char*);
  20. Func testFunc() {
  21. static int count = 100;
  22. static const char* const NAME = "James";
  23. class Test {
  24. public:
  25. static void process(const char* pName = NULL) {
  26. if (pName == NULL) pName = NAME;
  27. cout << pName << " Count is " << count-- << endl;
  28. }
  29. };
  30. return Test::process;
  31. }
  32. int main(int argc, char* argv[]) {
  33. ITest* pT = test();
  34. Func pF = testFunc();
  35. for (int i = 0; i < 10; i++) {
  36. (*pT)();
  37. pF((i % 2 == 0) ? NULL : "Fancy");
  38. }
  39. }

執行結果

  1. Count is 0
  2. James Count is 100
  3. Count is 1
  4. Fancy Count is 99
  5. Count is 2
  6. James Count is 98
  7. ...

C++ 是門非常靈活的語言,我們平時用到的僅是冰山一角。雖然工作關係四五年沒用它,但它依然是我最喜歡的語言之一。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved