C++里,我们通过在一个类中重载括号运算符的方法使用仿函数
2017-02-10 09:55
507 查看
在C++里,我们通过在一个类中重载括号运算符的方法使用一个函数对象而不是一个普通函数。
#include <iostream>
class compare_class
{
public:
bool operator()(int A, int B)const
{
std::cout<<"if "<< A<<"<"<<B << std::endl;
return A < B;
}
};
// Declaration of C++ sorting function.
//template<class ComparisonFunctor>
//void sort_ints(int* begin_items, int num_items, ComparisonFunctor c);
int main()
{
int items[]={4, 3, 1, 2};
compare_class functor;
//sort_ints(items, sizeof(items)/sizeof(items[0]), functor);
for (int i=0;i<3;i++)
{
std::cout<< functor(items[i],items[i+1]) << std::endl;
}
return 0;
}
#include <iostream>
class compare_class
{
public:
bool operator()(int A, int B)const
{
std::cout<<"if "<< A<<"<"<<B << std::endl;
return A < B;
}
};
// Declaration of C++ sorting function.
//template<class ComparisonFunctor>
//void sort_ints(int* begin_items, int num_items, ComparisonFunctor c);
int main()
{
int items[]={4, 3, 1, 2};
compare_class functor;
//sort_ints(items, sizeof(items)/sizeof(items[0]), functor);
for (int i=0;i<3;i++)
{
std::cout<< functor(items[i],items[i+1]) << std::endl;
}
return 0;
}
相关文章推荐
- 针对重载函数调用运算符的一个使用的例子,也就是重载()这个括号
- 在进行C#编程时候,有的时候我们需要判断一个字符串是否是数字字符串,我们可以通过以下两种方法来实现。 【方法一】:使用 try{} catch{} 语句。 我们可以在try语句块中试图
- 设计一个string类,通过重载“+=”运算符,实现对两个string类对象m1,m2的操作。
- 默认参数是C++的特性,C中不支持 —— 在C中通过默认参数列表使用默认参数的方法
- C++和Python使用同一个枚举的方法
- catch和throw同时使用---通过多个方法协作处理同一个异常
- C++库研究笔记——使用函数模板还是类模板?+ 一个类型重复问题的两种解决方法
- 分享:C++中四种类型转换运算符的使用方法
- 使用Django开发一个图书管理系统----04.通过admin模块管理我们的app和model
- 2.创建一个抽象类A,该类中包含一个求两个数之和抽象方法。创建一个子类B,在B中重写求和方法,且使用方法重载使得方法可以分别计算整数、双精度、字符串
- [C++]重载括号运算符
- 一个使用c++在lua中创建自定义数据类型的简易方法
- 今天发现了c++符号重载的一个非常实用的使用实例。
- C++中四种类型转换运算符的使用方法
- WCF X.b 操作引用了已经从 Y.b 操作导出的消息元素 [http://tempuri.org/:b]。可以通过更改方法名称或使用 OperationContractAttribute 的 Name 属性更改其中一个操作的名称...
- C++中四种类型转换运算符的使用方法
- C++中四种类型转换运算符的使用方法
- 一个使用c++在lua中创建自定义数据类型的简易方法
- 安卓应用开发通过java调用c++ jni的图文使用方法
- Android(安卓)开发通过NDK调用JNI,使用opencv做本地c++代码开发配置方法 边缘检测 范例代码