運算符重載——函數調用運算符重載

函數調用運算符重載:
  • 本質上就是重載雙括號()
  • 重載後的函數稱爲仿函數
  • 仿函數沒有固定寫法,非常靈活

代碼:

class MyPrint {
public:
    void operator()(string test) {
        cout << test << endl;
    }

    void operator()(int i) {
        cout << i << endl;
    }

};

class MyAdd {
public:
    int operator()(int a, int b) {
        return a + b;
    }
};

int main() {
    string s = "hello";

    MyPrint myPrint;
    MyAdd myAdd;

    myPrint(s);// 打印hello
    myPrint(myAdd(1,1));// 打印2

    //使用匿名對象來調用
    myPrint(MyAdd()(1,3));// 打印4

    return 0;
}

核心代碼:

    void operator()(string test) {
        cout << test << endl;
    }

    void operator()(int i) {
        cout << i << endl;
    }
    
    int operator()(int a, int b) {
        return a + b;
    }

需要注意的點:

  • 調用仿函數的方式:對象名(傳入相應參數);
  • 也可以用匿名對象來調用:類名()(傳入相應參數);

匿名對象的特點是執行完改行代碼後立刻調用析構函數,釋放對象空間,不再是執行完main方法後再調用對象的析構函數.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章