我正在创建一个比赛的 C++ 程序。
我有比赛课。每场比赛都有一个名称、距离和结果指针 vector (它是每个参与者的结果)。
结果类有一个指向参与者的指针和一个时间。
上课时间有小时、分钟和秒。
我想从最快时间到最慢时间对结果 vector 进行排序,因此为了比较结果我创建了函数 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;
}
最佳答案
您应该声明并定义Time::gethours()
作为常量成员函数。
class Time {
// ...
unsigned int gethours() const; // note the "const"
};
unsigned int Time::gethours() const { /* ... */ } // note the "const"
排序vector<Result*>
, 你需要
- 更改
Result::operator<()
采取const Result&
而不是Result&
作为参数 - 为
Result*
定义一个比较函数看起来像static bool cmpResultPtr(const Result* lhs, const Result* rhs) { return *lhs < *rhs; }
- 调用
sort(results.begin(), results.end(), cmpResultPtr);
函数cmpResultPtr()
可以在 .cpp 文件中定义,在 Race::sortResults()
的定义之前.
关于c++ - 对象指针的排序 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26708513/