如何在类(C )中作为参数传递函数

How to pass a function as parameter in class(C++)

本文关键字:参数 传递函数      更新时间:2023-10-16

我在做一个学生的清单:1.via名称2.via出生日期两者都只有不同的比较类型,其余的是相同的。因为我不希望使用模板类型来执行此操作:

class Student
{
    Date date;  // Date is a class
    Name name;  // Name is a class
   public:
    Date getDate() { return date; }
    Name getName() { return name; }
};
class ListOfStudent
{
    vector<Student> List;
   public:
    bool CompareDate(Date &d1, Date &d2);  // define d1<d2
    bool CompareName(Name &n1, Name &n2);  // define n1<n2
    void SortViaName()
    {
        for (int i = 0; i < List.size(); ++i)
            int min = i;
        for (int j = i + 1; j < List.size(); ++j)
        {
            if (CompareName(List[j].getName(), List[min].getName()))
                min = j;
        }
        if (min != i)
            swap(List[i], List[min]);
    }
    void SortViaDate()
    {
        for (int i = 0; i < List.size(); ++i)
            int min = i;
        for (int j = i + 1; j < List.size(); ++j)
        {
            if (CompareName(List[j].getDate(), List[min].getDate()))
                min = j;
        }
        if (min != i)
            swap(List[i], List[min]);
    }
    // Because i do not want to duplicate code so I do:
    template <typename T>
    void Sort(bool (*f)(T, T), T (*t)())
    {
        for (int i = 0; i < List.size(); ++i)
            int min = i;
        for (int j = i + 1; j < List.size(); ++j)
        {
            if ((*f)(DS[j].(*t)(), List[i].(*t)()))
                min = j;
        }
        if (min != i)
            swap(List[i], List[min]);
    }
};

它在模板功能上有问题,所以我需要您的支持。

为了使事情变得通用,设置内容的最简单方法是使CompareThing函数可选地使用Student&,而不是DateName

注意: CompareDateCompareName应该是 static或global ,这样您就可以将它们作为功能指针传递。

// We'll keep these
// Also they should either be static or global
bool CompareDate(Date &d1,Date &d2); //define d1<d2
bool CompareName(Name &n1,Name &n2); //define n1<n2
// Because these can both be used with Student, it's easy to template over them
bool CompareDate(Student &s1, Student &s2) {
    return CompareDate(s1.getDate(), s2.getDate()); 
}
bool CompareName(Student &s1, Student &s2) {
    return CompareName(s1.getName(), s2.getName()); 
}

然后,我们可以像这样写Sort

void Sort(bool(*compare)(Student&, Student&)) {
    std::sort(List.begin(), List.end(), compare); 
}
void SortViaName() {
    Sort(CompareName); 
}
void SortViaDate() {
    Sort(CompareDate); 
}

使用您的选择排序

我们可以编写Sort将功能作为参数,然后使用您的选择排序而不是std::sort

void Sort(bool (*compare)(Student&, Student&))
{
    for (int i = 0; i < List.size(); ++i) {
        int min = i;
        for (int j = i + 1; j < List.size(); ++j)
        {
            if (compare(List[j].getName(), List[min].getName()))
                min = j;
        }
        if (min != i)
            swap(List[i], List[min]);
    } 
}