zoukankan      html  css  js  c++  java
  • C++程序设计方法2:函数运算符重载

    函数运算符()重载

    函数运算符()也能重载,它使得对象看上去像是一个函数名

    ReturnType operator() (Parameters)

    {

    ......

    }

    ClassName Obj;

    Obj(real_parameters);

    //->obj.operator() (real_parameters);

    #include <iostream>
    using namespace std;
    
    class Test
    {
    public:
        int operator() (int a, int b)
        {
            cout << "operator() called." << a << " " << b << endl;
            return a + b;
        }
    };
    
    int main()
    {
        Test sum;
        int s = sum(3, 4);//sum对象看上去像是一个函数,故也成为“函数对象”
        cout << "a + b = " << s << endl;
        return 0;
    }
    #include <iostream>
    using namespace std;
    
    class Less
    {
        int thres_;
    public:
        Less(int th) :thres_(th) {}
        bool operator() (int);
    };
    
    bool Less::operator() (int value)
    {
        return (value < thres_);
    }
    
    void Filter(int *array, int num, Less fn)
    {
        for (int i = 0; i < num; i++)
        {
            if (fn(array[i]))
                cout << array[i] << " ";
        }
        cout << endl;
    }
    
    int main()
    {
        int array[5] = { 1,-4,10,0,-1 };
        int thres;
        cout << "thres:";
        cin >> thres;
        Less less_than(thres);
        Filter(array, 5, less_than);
        return 0;
    }
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    NVIDIA GTC照片
    渲染农场云云
    Visual Studio 2008 SP1键盘F10单步调试超慢解决方法
    跨DLL操作fopen的返回值导致出错
    OSL LLVM 3.3 Related Changes
    Windows上编译OpenShadingLanguage
    Windows上编译OpenImageIO
    Windows上编译LLVM 3.2
    Windows上编译OpenEXR
    Windows上编译libtiff
  • 原文地址:https://www.cnblogs.com/hujianglang/p/6629053.html
Copyright © 2011-2022 走看看