2012-03-06 3 views
0

빠른 정렬 또는 가능한 병합 정렬 알고리즘을 사용하여 문자열 배열을 정렬하려면 다음 연산자를 오버로드하려고합니다. 단일 클래스에서 모든 함수가 있지만 "이 연산자 함수에 대해 너무 많은 매개 변수"오류가 발생합니다. 사실 하나의 매개 변수 만 허용합니다. 문제를 찾아보고 포럼에서 누군가가 클래스 내부에서 연산자를 오버로드 할 때 매개 변수 하나만 사용할 수 있다고 말했습니다. 이것은 나에게별로 의미가 없습니다. 오버로드를 위해 두 개의 매개 변수가 필요하므로 문자열을 비교하려고합니다. 수업 외부의 운영자에게 과부하가 걸릴 수 있습니까? 어떻게 작동합니까? 운영자에 대한이진 연산자 오버로드 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; 
} 
+0

'std :: string'을 비교하기위한 표준 연산자를 바꾸시겠습니까? 아니면 당신의 타입을'std :: string'과 비교하려고합니까? –

답변

5

서명이 잘못된 : 여기

내 코드의 당신이 연산자를 오버로드

bool operator<=(string a, string b); 
bool operator<(string a, string b); 
bool operator>(string a, string b); 
  1. - 당신이 그것을 만해야, 멤버 함수로 구현 하나의 인수를 받아 들인다. (다른 사람은 )
  2. 비회원 기능 (즉, 친구), th 두 인수를 제공 할 수 있지만 기존 연산자 (이미 std::string에 정의되어있는 연산자)와 일치 할 수 없으며 테스트를 위해 일반적으로 클래스를 lhs 및 rhs로 받아 들여야합니다. 좌측이 this 포인터로 전달되기 때문에
+0

Oh, o.k. 그렇다면 첫 번째 매개 변수를 선언하면 중복 될 것입니다. – rocklandcitizen

+0

@rocklandcitizen - 알겠습니다. – prelic

+1

@rocklandcitizen은 중복하지 않아도됩니다. 왼손 피연산자 ("첫 번째 매개 변수")는 클래스의 인스턴스이며,'this' 포인터로 접근 할 수 있습니다. – bonsaiviking

0

그것은 오직 하나 개의 인수를 취하는.

+0

고맙습니다. 그것은 매력처럼 작동합니다. – rocklandcitizen

+0

@rocklandcitizen - 다행스럽게도 당신을 위해 일했습니다! – prelic

0

연산자를 오버로드하려면 연산자가 왼쪽 피연산자의 메서드 여야합니다. C++은 인수 (피연산자)의 유형에 따라 함수 (및 연산자)를 선택합니다. 클래스 내에서 왼쪽 피연산자는 클래스의 인스턴스이며 this 포인터로 사용할 수 있으므로 오른쪽 피연산자 만이 연산자에 대한 인수로 지정 될 수 있습니다. 당신의 예에서

,이 작업을 수행 할 수 있습니다 : 문자열로 Preprocessing 객체를 비교하는 <= 연산자를 정의 할

class Preprocessing { 
    public: 
     bool operator<=(string b); 
}; 

. 문자열 비교 연산자를 오버로드해야하는 경우 내 지식이 아닌 std::string 클래스를 수정해야합니다.

1

클래스 내부에있는 operator은 무엇이든 그 연산자를 해당 클래스의 인스턴스 및 선택적으로 매개 변수에 적용하는 특별한 의미가 있습니다.

예에서 operator<=Preprocessing 클래스의 인스턴스를 string과 비교해야합니다.

class Preprocessing 
{ 
public: 
    bool operator<=(string a); 

private: 
    string aStringField; 
} 

일반적으로 당신은 매개 변수를 사용하여 인스턴스를 비교하기 위해 운영자 방법 본체 내부에 this를 사용

bool Preprocessing::operator<=(string a) 
{ 
    return this->aStringField.length() <= a.length(); 
} 

그리고 당신은 그것을 호출

:

Preprocessing p; 
if (p <= "a string") 
    // ... 

에 해당하는 어느

Preprocessing p; 
if (p.operator<=("a string")) 
    // ... 

"포인트 구문"이 필요없는 연산자를 제공하려는 경우 클래스 외부에있는 연산자는 friend입니다.

class Preprocessing 
    { 
    public: 
     friend ostream& operator<<(ostream&, const Preprocessing&); 

    private: 
     string aStringField; 
    }