2014-11-03 2 views
1

나는 경주의 C++ 프로그램을 만들고 있습니다. 나는 경주 등급을 가지고있다. 각 종족에는 결과 포인터의 이름, 거리 및 벡터 (각 참가자의 결과)가 있습니다. 결과 클래스에는 참가자를 가리키는 포인터와 시간이 있습니다. 수업 시간은시, 분, 초입니다. 가장 빠른 시간에서 가장 느린 시간까지의 결과 벡터를 정렬하려면 결과를 비교하기 위해 bool operator <(Result& res2) const 클래스를 result에 생성했습니다.개체 포인터의 벡터 정렬

.h 파일의 모든 기능이 구현되었으므로 그 중 일부만 보여주고 있습니다.

나는 sortResults 함수가 올바르지 않지만 함수 operator<은 내가 해결 방법을 모른다는 오류를주고있다. 모든 if 문에서 다음과 같은 오류가 발생합니다.이 줄의 여러 마커

- passing 'const Time' as 'this' argument of 'unsigned int Time::getHours()' discards qualifiers [- 
fpermissive] 
- Line breakpoint: race.cpp [line: 217] 
- Invalid arguments ' Candidates are: unsigned int getHours() ' 

내가 잘못하고있는 것을 말해 줄 수 있습니까?

.H 파일 :

class Time 
{ 
    unsigned int hours; 
    unsigned int minutes; 
    unsigned int seconds; 
public: 
    Time(unsigned int h, unsigned int m, unsigned int s, unsigned int ms); 
    Time(); 
    unsigned int gethours(); 
    unsigned int getMinuts(); 
    unsigned int getSeconds(); 
    string show(); 
}; 

class Participant { 
    string name; 
    unsigned int age; 
    string country; 
public: 
    Participant(string n, unsigned int a, string c); 
    string getName(); 
    string getCountry(); 
    int getAge(); 
    string show() const; 
}; 

class Result { 
    Participant *part; 
    Time time; 
public: 
    Result(Participant *p, Time t); 
    Participant *getParticipant() const; 
    Time getTime(); 
    string show(); 
    bool operator <(Result& res2) const; 
}; 

class Race { 
    string name; 
    float distance; 
    vector<Result *> results; 
public: 
    Race(string nm, float dist); 
    string getName(); 
    void setName(string nm); 
    float getDistance(); 
    vector<Result *> sortResults(); 
    void addResult(Result *r); 
    string showRaceResults(); 
    string show(); 
}; 

.cpp 파일 :

bool Result::operator <(Result& res2) const { 
    if (time.gethours() < res2.getTime().gethours()) 
     return true; 
    else { 
     if (time.gethours() > res2.getTime().gethours()) 
      return false; 
     else { 
      if (time.getMinutes() < res2.getTime().getMinutes()) 
       return true; 
      else { 
       if (time.getMinutes() > res2.getTime().getMinutes()) 
        return false; 
       else { 
        if (time.getSeconds() < res2.getTime().getSeconds()) 
         return true; 
        else { 
          return false; 
         } 
       } 
      } 
     } 
    } 
} 

vector<Result *> Race::sortResults() { 
    sort (results.begin(), results.end(), operator <); 
return results; 
} 
+0

제발, 제발, 제발'제발'모든'else' cruft 제거'연산자''. 당신의 기능은 훨씬 더 멋지게 보일 것입니다. –

+0

bool Result :: operator <(Result & rhs) const {return std :: make_tuple (time.gethours(), time.getMinutes(), time.getSeconds()) Jarod42

+0

연산자를 사용하여 벡터를 정렬하는 것이 옳은가요? 또는 bool Result :: lowerTime (Result & res1, Result & res2) const와 같은 함수를 만들어야 결과 벡터를 정렬 할 수 있습니까? 가장 좋은 방법은 무엇일까요? – user2880113

답변

2

당신은 선언하고 Time::gethours() 상수 멤버 함수를 정의해야합니다. vector<Result*>를 정렬하려면

class Time { 
// ... 
    unsigned int gethours() const; // note the "const" 
}; 

unsigned int Time::gethours() const { /* ... */ } // note the "const" 

, 당신은

  • static bool cmpResultPtr(const Result* lhs, const Result* rhs) { return *lhs < *rhs; } 같은 전화를 보이는 Result*에 대한 비교 함수를 정의 매개 변수
  • const Result&보다는 Result&를 취할

    1. 변경 Result::operator<() 필요 sort(results.begin(), results.end(), cmpResultPtr);

    함수 cmpResultPtr()Race::sortResults()의 정의 앞에 .cpp 파일에 정의 될 수 있습니다.

  • +0

    고맙습니다. 그것은 operator user2880113

    +0

    @ user2880113 연산자 <를 정의했다면 처음 두 매개 변수로 sort()를 호출하고 세 번째 매개 변수는 건너 뜁니다. – timrau

    +0

    다음과 같은 함수를 만들었습니다 : _italic_ ** bold **'void Race :: sortResults() { \t sort (results.begin(), results.종료()); }' – user2880113

    1

    연산자 <을 const로 선언하지만 호출하는 Time :: getHours에는 동일한 선언이 없습니다. 컴파일러에서 이것은 getHours가 연산자 <의 constness를 위반하는 시간 구성원의 값을 변경할 수 있음을 의미합니다.