【发布时间】:2012-03-24 05:01:39
【问题描述】:
我正在尝试重载以下运算符以使用快速排序或可能的合并排序算法对字符串数组进行排序。我的所有函数都在一个类中,但出现“此运算符函数的参数过多”错误。事实上,它只会接受一个参数。我查了这个问题,在论坛上有人说在类中重载运算符时只能使用一个参数。这对我来说没有多大意义。我正在尝试比较字符串,所以我需要两个参数来进行重载。我是否应该重载类外的运算符,这将如何工作?
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Preprocessing
{
public:
void readFile(string list[], int size);
void quickSort(int list[], int lowerBound, int upperBound);
void swapItem(int &a, int &b);
//These are the overloading functions I'm trying to implement
bool operator<=(string a, string b);
bool operator<(string a, string b);
bool operator>(string a, string b);
};
void Preprocessing::readFile(string list[], int size)
{
ifstream myFile;
myFile.open("words.txt");
for (int i = 0; i < size; i++)
{
myFile >> list[i];
}
myFile.close();
}
void Preprocessing::quickSort(int list[], int lowerBound, int upperBound)
{
int i, j, pivot;
i = lowerBound;
j = upperBound;
pivot = list[(i + j) / 2];
while (i <= j)
{
while(list[i] < pivot)
{
i = i + 1;
}
while (list[j] > pivot)
{
j = j - 1;
}
if (i <= j)
{
swapItem(list[i], list[j]);
i = i + 1;
j = j - 1;
}//end if
}//end outter while
if (lowerBound < j)
{
quickSort(list, lowerBound, j);
}
if (i < upperBound)
{
quickSort(list, i, upperBound);
}//end recursive if
}//end function
void Preprocessing::swapItem(int &a, int &b){
int tmp;
tmp = a;
a = b;
b = tmp;
}
bool Preprocessing::operator<=(string a, string b)
{
if (a.compare(b) > 0)
return false;
else if (a.compare(b) == 0)
return true;
else
return true;
}
bool Preprocessing::operator<(string a, string b)
{
if (a.compare(b) > 0)
return false;
else if (a.compare(b) == 0)
return true;
else
return true;
}
bool Preprocessing::operator>(string a, string b)
{
if (a.compare(b) > 0)
return false;
else if (a.compare(b) == 0)
return true;
else
return true;
}
【问题讨论】:
-
您是否尝试替换标准运算符来比较
std::string?或者您是否想让您的类型与std::string相媲美?