I'm trying to compare two objects but I keep on getting the error:
binary '==': 'robot' does not define this operator or a conversion to a type acceptable to the predefined operator
This is my cpp file:
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";
}
This is my header file:
#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
For your own class types you can define operators for it, where operator==
is one of them.
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
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.