c++ - 如何在涉及类的 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;
}
解决方案
重载运算符的全部意义在于您不必像函数调用那样将其拼写出来。
所以对于这一行:
if (blog[j].operator<())
除了您缺少 to 的参数这一事实之外,operator<
您还可以像这样比较 2 个Blog
对象:
if (blog[j] < blog[i])
如果您明确想要拼出操作员调用,您可以执行以下操作:
if (blog[j].operator<(blog[i]))
推荐阅读
- ruby-on-rails - Rails 5:Stripe 检索或创建产品
- sql - SQL 入口和出口点查询的特定问题
- android - Firebase Firestore addSnapshotListener() 可能导致“FragmentManager 已在执行事务”错误
- php - 如何使用 JWT 身份验证获取登录用户信息?
- java - 文件夹挂载后出现 FileNotFoundException?
- bash - 尽管昨天工作,但在 bashrc 文件中保存的别名无法正常工作,并且 echo ~ 返回 /h/
- javascript - 如何在用作 Dialogflow webhook 的 Google Cloud Function 中达到 Promise 拒绝选项?
- python-3.x - 使用脚本(Python,shell)修改文件
- php - 为什么以下代码无法在实际服务器上运行,但在 localhost 上运行良好?
- sql - 将 select 语句放在 for 循环中 - sql