要把函数作为参数传递时,有两种方法:1.函数指针;2.仿函数.

函数指针的方法比较常用:

复制代码
Code
typedef int (*pf)(int,int);
int f(pf p,int a,int b){
    
return p(a,b);
}
int add(int a,int b){
    
return a+b;
}
int main(){
    cout
<<f(add,1,2)<<endl;
}
复制代码

但用函数指针时,它无法持有自己的状(局部状态,local states),仿函数就克服了这个缺点.

仿函数:

 

复制代码
template<class T>
class Sum{
    T res;
public:
    Sum(T i
=0):res(i){}
    
void operator()(T x){
        res
+=x;
    }
    T result() 
const{
        
return res;
    }
};

template
<class T>
struct testplus{
    T 
operator()(const T& x,const T& y)const{
        
return x+y;
    }
};
int main(){
    list
<double> l;
    l.push_back(
1.0);
    l.push_back(
2.0);
    Sum
<double> s;
    s
=for_each(l.begin(),l.end(),s);
    cout
<<"the sum is"<<s.result()<<endl;
    
//cout<<plus<int>(1,2)<<endl;//error for lost ()
    testplus<int> plusobj;
    cout
<<plusobj(1,2)<<endl<<testplus<int>()(2,2);
}
复制代码

 

posted on   CUCmehp(likesmiles)  阅读(1090)  评论(0编辑  收藏  举报
编辑推荐:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
< 2009年2月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
1 2 3 4 5 6 7
8 9 10 11 12 13 14

点击右上角即可分享
微信分享提示