https://blog.csdn.net/infoworld/article/details/38901127

 

在C++里,我们通过在一个类中重载括号运算符的方法使用一个函数对象而不是一个普通函数。

1、表达式格式

HWND operator ()() const throw()
{
    return m_hWnd;
}

与类型改变表达式格式区别:

operator HWND() const throw()
    {
        return m_hWnd;
    }

案例:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

template <typename T>

class search_num
{
    T m_val;
public:
    search_num(T value):m_val(value) { cout << " construct " <<value<< endl; }
    bool operator()(const T val){ 
        cout << "opeatorr()" << endl; 
        return (m_val == val);
    }
};

int main()
{
    vector<int> v;
    for (int i = 1; i < 6; i++)
    {
        v.push_back(i);
    }

    vector<int>::iterator it = find_if(v.begin(), v.end(), search_num<int>(4));
    if (it != v.end())
    {
        cout << " find num " << *it << endl;

    }
    else
    {
        cout << "not find the num" << endl;
    }
    return 0;
}
View Code

相关文章:

  • 2022-12-23
  • 2021-08-07
  • 2022-01-21
  • 2022-12-23
  • 2021-11-05
  • 2021-12-20
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-08
  • 2022-12-23
  • 2022-01-27
相关资源
相似解决方案