您的位置:首页 > 编程语言 > C语言/C++

C++之可调用对象

2015-07-15 15:01 330 查看
C++中的可调用对象分为以下几种:

函数

函数指针

lambda表达式

bind创建的对象

重载了函数调用运算符(即“()”)的类

函数、函数指针不再介绍。lambda表达式与bind创建的类参考——lambda表达式和bind函数。

这里通过例子说明一下lambda表达式与重载了函数调用运算符的类有一些相通之处。

lambda是函数对象,是一个可调用对象。编译器在解释lambda表达式时,将其解释为一个未命名类的未命名对象,该类重载了函数调用运算符。
1、首先声明一个类,重载函数调用运算符。成员变量根据实际情况而定。

/**


* 重载了函数调用运算符的类


*/


classSizeComp


{


public:


SizeComp(std::size_t sz): size(sz){}


voidoperator()(const string & str)const


{


if(str.size()>= size)


{


cout << str << endl;


}


}


private:


std::size_t size;


};


2、创建类对象,并给需要用到的变量进行赋值。

void testInvoke2nd()


{


vector<string> strVec ={"1","12","123","1234","12345","123456","1234567"};


std::size_t sz =5;




cout <<"lambda表达式:"<< endl;


auto comp =[sz](const string & str)->void


{


if(str.size()>= sz)


{


cout << str << endl;


}


};


for_each(strVec.begin(), strVec.end(), comp);




cout <<"()运算符重载:"<< endl;


for_each(strVec.begin(), strVec.end(),SizeComp(sz)); // 先是调用构造函数创建一个临时对象


}


对可调用对象的使用

#include<iostream>


#include<functional>


#include<map>




usingnamespace std;




/**< 可调用对象——函数*/


/**


* 若进行函数重载则不能直接使用函数名


* 会产生二义性


* 此时考虑函数指针或其他的实现方式


*/


//implements "+" operation


constint addInt(constint x,constint y)


{


return x + y;


}




/**< 可调用对象——重载了调用运算符的类*/


//implements "-" operation


struct minusInt


{


constintoperator()(constint x,constint y)


{


return x - y;


}


};




//函数指针所指向的函数


constint dividesFunc(constint x,constint y)


{


return x / y;


}




void testFunction()


{


/**< 可调用对象——lambda表达式*/


//implements "*" operation


auto multipInt =[](constint x,constint y)->constint


{


return x * y;


};




/**< 可调用对象——函数指针*/


//implements "/" operation


constint(*dividesInt)(int,int)= dividesFunc;


// dividesInt = multipInt; // 说明lambda是一个函数对象




/**


* function<int(int, int)>的原型是function<T>


* @brief 存储可调用对象(该对象的调用形式应该与T相同)


* @param T 函数类型(返回值类型,参数个数及)


   */


map<string, function<int(int,int)>> binops =


{


{"+", addInt},/* 函数名默认转化为函数指针类型*/


{"-", minusInt()},/* 创建一个类对象*/


{"*", multipInt},/* lambda表达式类型的对象*/


{"/", dividesInt}/* 函数指针*/


};




cout << binops["+"](10,5)<< endl


<< binops["-"](10,5)<< endl


<< binops["*"](10,5)<< endl


<< binops["/"](10,5)<< endl;


}




int main()


{


testFunction();


return0;


}


来自为知笔记(Wiz)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: