C++ 函数符()

#include<iostream>  
using namespace std;  

class Plus{  
private:  
    double y;  
public:  
    Plus():y(0){}  
    Plus(double y):y(y){}  
    double operator()(double x){  
        return x * y;  
    }  
};  

int main(){  
    Plus obj(6);  
    double x = 4;  
    cout<<obj(x)<<endl;  
    return 0;  
}

/*
24
请按任意键继续. . .
*/

C++ 函数符

https://blog.csdn.net/cloud323/article/details/75042960

 分类:

一,什么是函数符?

函数对象也叫函数符,函数符是可以以函数方式与()结合使用的任意对象。这包括函数名、指向函数的指针和重载了()运算符的类对象。

 

二,使用重载了()运算符的类对象

重载的()运算符能像函数那样使用Plus对象

 

[cpp] view plain copy
 
  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Plus{  
  5. private:  
  6.     double y;  
  7. public:  
  8.     Plus():y(0){}  
  9.     Plus(double y):y(y){}  
  10.     double operator()(double x){  
  11.         return x * y;  
  12.     }  
  13. };  
  14.   
  15. int main(){  
  16.     Plus obj(6);  
  17.     double x = 4;  
  18.     cout<<obj(x)<<endl;  
  19.     return 0;  
  20. }  

      

三,如何声明for_each()的第三个参数

for_each()将指定的函数应用于区间中的每个成员

 

[cpp] view plain copy
 
  1. vector<int> books;  
  2. for_each(books.begin(), books.end(), ShowReview);  

如何声明第三个参数呢?不能把它声明为函数指针,因为函数指针指定了参数类型,STL通过使用模板解决了这个问题。

 

四,自定义对数组进行处理的函数

 

[cpp] view plain copy
 
  1. template<typename Function>  
  2. void  process(vector<int> &num, Function f){  
  3.     for(int i = 0; i < num.size(); i ++){  
  4.         f(num[i]);  
  5.     }  
  6. }  
  7.   
  8. //声明一个函数符, 输出数组中的每个元素  
  9. class Output{  
  10. public:  
  11.     void operator()(int x){  
  12.         cout<<x<<endl;  
  13.     }  
  14. };  
  15.   
  16. int main(){  
  17.     int a[5] = {1, 2, 3, 4, 5};  
  18.     vector<int> num(&a[0], &a[5]);  
  19.     Output out;  
  20.     process(num, out);  
  21.     return 0;  
  22. }  

 

posted @ 2018-04-02 17:37  sky20080101  阅读(220)  评论(0)    收藏  举报