我想按如下方式在多态性中实现功能对象:
#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());
}
但是它有一个错误消息“没有重载函数“sort”的实例匹配参数列表”
我认为抽象类不能有实例。 我该如何解决?
最佳答案
std::sort
想要复制排序函数。
有一个标准类可以“包装”引用并使其可复制; std::ref
.
#include <memory>
... and then ...
sort(arr, arr + 10, std::ref(c));
关于c++ - 多态中的函数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67467289/