Я пытаюсь сравнить два объекта, но я продолжаю получать сообщение об ошибке:
двоичный '==': 'робот' не определяет этот оператор или преобразование в тип, приемлемый для предопределенного оператора
Это мой файл cpp:
void move(const robot r, vector<robot>& vec_r) {
// 0 = north, 1 = east, 2 = south, 3 = west
int x = r.xpos();
int y = r.ypos();
// move the robot depending on which direction it's facing
if (direction == 0) { ++y; }
else if (direction == 1) { ++x; }
else if (direction == 2) { --y; }
else if (direction == 3) { --x; }
// check if space is occupied and also if in enemy team, delete the robot
for (auto &p : vec_r) {
if (x == p.xpos() && y == p.ypos() /* && r.teamNo() == p.teamNo() */ ) {
find(vec_r.begin(), vec_r.end(), [&]() {
return robot(r.id(), r.teamNo(), x, y) == robot(p.id(), p.teamNo(), p.xpos(), p.ypos());
});
}
}
cout << r.id() << ' ' << r.teamNo() << ' ' << x << ' ' << y << ' ' << "\n";
}
Это мой заголовочный файл:
#ifndef ROBOT_H
#define ROBOT_H
#include <vector>
#include <string>
class robot {
int _id;
int _teamNo;
int _xpos;
int _ypos;
public:
robot(const int &id, int teamNo, int xpos, int ypos) :
_id(id), _teamNo(teamNo), _xpos(xpos), _ypos(ypos) {}
// Accessor functions for robot details
int id() const { return _id; }
int teamNo() const { return _teamNo; }
int xpos() const { return _xpos; }
int ypos() const { return _ypos; }
int getDirection() { return direction; };
int Compare(const robot& r) const;
bool operator == (const robot& r) const {
return 0 == Compare(r);
}
private:
int direction = 0;
};
#endif
Для ваших собственных типов классов вы можете определить для него операторы, где operator== — один из них.
class robot {
// ... all your other stuff
public:
bool operator==(const robot& other) const {
return _id == other._id; // Use whatever logic makes sense for you here
}
};
Я не могу воспроизвести вашу проблему; кажется, вы правильно определили свой оператор сравнения. Однако ваша функция move не компилируется, и сообщение об ошибке немного похоже на то, что вы описываете; мне непонятно, что должна делать конструкция с find, но, похоже, вы искали find_if?