关于stackoverflow的许多主题都解决了这个问题,但是对于我的示例,我无法使其正确。我有一个班级活动,以及活动发生的时间。我想根据该时间将这些对象排序为向量。
我首先开始实现operator <,但是随后编译器给出了以下错误:
错误1错误C2582:'操作符='函数在'事件'中不可用c:\ program files(x86)\ microsoft visual studio 12.0 \ vc \ include \ algorithm 3009 1 sorting
因此,我添加了运算符=
以下是我使用的代码:
#include <algorithm> // std::sort
#include <vector> // std::vector
using namespace std;
class Event{
public:
const double time;
Event(double);
bool operator<(const Event&);
bool operator=(const Event&);
};
Event::Event(double time) :
time(time){
}
bool Event::operator<(const Event& rhs)
{
return this->time < rhs.time;
}
bool Event::operator=(const Event& rhs)
{
return this->time == rhs.time;
}
int main() {
vector<Event> vector;
Event e1 = Event(10);
Event e2 = Event(5);
Event e3 = Event(7);
vector.push_back(e1);
vector.push_back(e2);
vector.push_back(e3);
sort(vector.begin(), vector.end());
return 0;
}
调试时,我发现我的对象根本没有排序。它们按照我添加它们的顺序。以下是“ vector”变量的摘录:
[0] {time=10.000000000000000 } Event
[1] {time=5.0000000000000000 } Event
[2] {time=7.0000000000000000 } Event
我有以下问题:
问题在于,Event
由于const double time
成员的缘故,无法分配您的类的对象。由于成员是const
不能修改的,因此不能sort
在带有Event
对象的容器上使用,因为排序需要分配。
删除const
或重新考虑您要做什么。顺便说一句,您混淆赋值运算符(operator=
,这是sort
需要) with equality operator (
operator ==`的东西)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句