回調函數、仿函數和lambda表達式的優劣比較

#include <iostream>

int add(int a,int b)
{
	return a+b;
}

struct Obj
{
  int operator()(int a,int b)
  {
	return a+b;
  }
};
class OperatingNumbers
{
private:
	int num1;
	int num2;
public:
	explicit OperatingNumbers(int a=1,int b=1):num1(a),num2(b){}
	~OperatingNumbers(){}
public:
	int getNumbyRtnFunction(int (*p)(int a,int b))
	{
		return p(num1,num2);  //利用回調函數來求和
	}

	int getNumbyObj(Obj obj)
	{
		return obj(num1,num2);  //利用函數對象,即仿函數來求和
	}

	int getNumbyLambda()
	{
		return [](int a,int b)->int{ return a+b;}(num1,num2); //利用lambda表達式求和
	}
};


int main(int argc, char* argv[])
{
	OperatingNumbers oNum(2,3);
	Obj o;
	std::cout<<oNum.getNumbyRtnFunction(add)<<std::endl;
	std::cout<<oNum.getNumbyLambda()<<std::endl;
	std::cout<<oNum.getNumbyObj(o)<<std::endl;

	getchar();

	return 0;
}
相關文章
相關標籤/搜索