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
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cloud323/article/details/75042960
一,什么是函数符?
函数对象也叫函数符,函数符是可以以函数方式与()结合使用的任意对象。这包括函数名、指向函数的指针和重载了()运算符的类对象。
二,使用重载了()运算符的类对象
重载的()运算符能像函数那样使用Plus对象
- #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;
- }
三,如何声明for_each()的第三个参数
for_each()将指定的函数应用于区间中的每个成员
- vector<int> books;
- for_each(books.begin(), books.end(), ShowReview);
如何声明第三个参数呢?不能把它声明为函数指针,因为函数指针指定了参数类型,STL通过使用模板解决了这个问题。
四,自定义对数组进行处理的函数
- template<typename Function>
- void process(vector<int> &num, Function f){
- for(int i = 0; i < num.size(); i ++){
- f(num[i]);
- }
- }
- //声明一个函数符, 输出数组中的每个元素
- class Output{
- public:
- void operator()(int x){
- cout<<x<<endl;
- }
- };
- int main(){
- int a[5] = {1, 2, 3, 4, 5};
- vector<int> num(&a[0], &a[5]);
- Output out;
- process(num, out);
- return 0;
- }

浙公网安备 33010602011771号