C++ 多态性中的功能对象
我想在多态性中实现函数对象,如下所示:C++ 多态性中的功能对象,c++,sorting,polymorphism,function-object,C++,Sorting,Polymorphism,Function Object,我想在多态性中实现函数对象,如下所示: #include <algorithm> #include <iostream> using namespace std; struct Compare { virtual bool operator() (int, int) const = 0; }; struct Less : public Compare { bool operator() (int i, int j) const {
#include <algorithm>
#include <iostream>
using namespace std;
struct Compare {
virtual bool operator() (int, int) const = 0;
};
struct Less : public Compare {
bool operator() (int i, int j)
const {
return (i < j);
}
};
struct Greater : public Compare {
bool operator() (int i, int j)
const {
return (i > j);
}
};
void f(const Compare& c) {
int arr[10] = { 4,2,6,7,1,3,5,9,8,0 };
sort(arr, arr + 10, c);
for (int i = 0; i < 10; ++i)
cout << arr[i] << " ";
}
int main()
{
f(Less());
f(Greater());
}
#包括
#包括
使用名称空间std;
结构比较{
虚拟布尔运算符()(int,int)常量=0;
};
无结构:公共比较{
布尔运算符()(int i,int j)
常数{
返回(ij);
}
};
空f(常数比较和c){
int-arr[10]={4,2,6,7,1,3,5,9,8,0};
排序(arr,arr+10,c);
对于(int i=0;i<10;++i)
cout按值获取comparator参数;您不能向它传递像Compare
这样的抽象类。您可以直接向它传递Less
或Greater
您可以制作f
模板
template <typename C>
void f(const C& c) {
int arr[10] = { 4,2,6,7,1,3,5,9,8,0 };
sort(arr, arr + 10, c);
for (int i = 0; i < 10; ++i)
cout << arr[i] << " ";
}
std::sort
想要复制订购功能
有一个标准类“包装”引用并使其可复制;std::ref
#include <memory>
... and then ...
sort(arr, arr + 10, std::ref(c));
#包括
……然后。。。
排序(arr,arr+10,标准::参考(c));
#include <memory>
... and then ...
sort(arr, arr + 10, std::ref(c));