首页 > 解决方案 > 如何比较两个对象?

问题描述

我正在尝试比较两个对象,但我不断收到错误:

二进制 '==': '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

标签: c++

解决方案


对于您自己的类类型,您可以为其定义运算符,其中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
    }
};

推荐阅读