首页 > 解决方案 > 如何在涉及类的 C++ 函数中进行 selectionSort,并且对数组进行操作 < 的重载?

问题描述

我不知道如何将我的 operator< 函数调用到我的 selectionSort 函数中。selectionSort 函数应该将数组中的博客对象从最新到最旧排列。operator< 函数用于比较自每个博客的博文发布以来经过的天数。我可以使用一些帮助来设置调用 operator< 函数的 selectionSort 函数。

错误包括:-在函数 'void selectionSort(Blog*, int)' 中:-[Error] 'class Blog' 没有名为 'operator<' 的成员 -[Error] 'displayData' 未在此范围内声明

void selectionSort(Blog blog[], int numBlogs)
{
    Blog temp;
    int minIndex=0;
    for (int i=0; i<numBlogs-1; i++)
    {
        minIndex = i;
        for (int j=i+1; j<numBlogs; j++)
        if (blog[j].operator<())
            minIndex=j;
                        //swap positions i and minIndex
        temp = blog[i];
        blog[i] = blog[minIndex];
        blog[minIndex] = temp;
        displayData(blog, numBlogs);
        
        
    }
}

    bool Blog::operator< (const Blog &right) const
        {
            if (daysElapsed() < right.daysElapsed())//comparing two objects that are in the blog[]
                return true;
           else
               return false;
        }

标签: c++operator-overloadingselection-sort

解决方案


重载运算符的全部意义在于您不必像函数调用那样将其拼写出来。

所以对于这一行:

if (blog[j].operator<())

除了您缺少 to 的参数这一事实之外,operator<您还可以像这样比较 2 个Blog对象:

if (blog[j] < blog[i])

如果您明确想要拼出操作员调用,您可以执行以下操作:

if (blog[j].operator<(blog[i]))

推荐阅读