首页 > 解决方案 > 多态中的函数对象

问题描述

我想在多态中实现功能对象,如下所示:

#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());
}

但它有一条错误消息“没有重载函数“排序”的实例与参数列表匹配”

我认为抽象类不能有实例。我该如何解决?

标签: c++sortingpolymorphismfunction-object

解决方案


std::sort按值获取比较器参数;你不能像Compare它一样传递一个抽象类。您可以传递LessGreater直接传递给它。

你可以制作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] << " ";
}

然后传递Less或传递Greater给它,例如:

f(Less());
f(Greater());

居住


推荐阅读