我想重載以下運算符使用快速排序或可能合併排序算法排序字符串數組。我有我的所有功能在一個類,但我得到「這個運算符功能太多參數」錯誤。的確,它只會接受一個參數。我查了一下這個問題,並在一個論壇上有人說,你只能在一個班級裏面重載一個操作符時使用一個參數。這對我來說沒有多大意義。我試圖比較字符串,所以我需要重載的兩個參數。我是否應該讓班級以外的操作員負擔過重,這將如何工作?二進制運算符重載C++
這裏是我的代碼:
#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'相媲美? – 2012-03-06 17:18:10