二进制运算符重载C++

roc*_*zen 0 c++ operator-overloading

我正在尝试重载以下运算符,以使用快速排序或可能的合并排序算法对字符串数组进行排序.我将所有函数都放在一个类中,但是我得到了"这个操作符函数的参数太多"错误.实际上,它只接受一个参数.我查找了问题并在论坛中有人说你在类中重载一个操作符时只能使用一个参数.这对我来说没什么意义.我正在尝试比较字符串,所以我需要两个参数进行重载.我是否应该超出班级以外的操作员,这将如何工作?

这是我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Nim*_*Nim 5

运算符的签名不正确:

bool operator<=(string a, string b);
bool operator<(string a, string b);
bool operator>(string a, string b);
Run Code Online (Sandbox Code Playgroud)
  1. 当你重载一个操作符 - 并将它实现为一个成员函数时,它应该只接受一个参数(另一个要比较的东西)
  2. 如果是非成员函数(即朋友),那么你可以提供两个参数,但它不能匹配一个现有的运算符(已经定义了一个std::string),并且通常应该接受你的类作为lhs和rhs进行测试.