c++ - 如何比较两个对象?
问题描述
我正在尝试比较两个对象,但我不断收到错误:
二进制 '==': 'robot' 未定义此运算符或转换为预定义运算符可接受的类型
这是我的 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
}
};
推荐阅读
- android - 只能将来自 firebase 的最后一个子子项显示到我的回收站视图(已更新)
- javascript - 解释为什么这个解决方案不会返回一个承诺?JS
- kubernetes - Kubectl 配置更改不会通过 Rancher CLI 保存
- reactjs - react-native run-android 未连接到日志,发送旧版本
- c# - WPF 本地化多种语言 ResourceDictionary 与资源文件 (.RESX)
- python - 向 Ray Tune 状态表添加更多指标(Python、PyTorch)
- c++ - 为什么函数得到相同的值得到阶乘?
- c++ - 如何使用omniORB 构建程序?
- excel - Excel 工作簿功能可删除单元格中的现有图表并替换为新图表
- python - 如何在 tkinter 窗口中使用不在 ASCII 表中的符号?