Ven*_*nom 0 c++ vector operator-overloading
我有一个向量填充自定义类型的值,并且find()算法抱怨它无法为值比较找到合适的==运算符.我已经实现了这样:
bool Ship::operator==(const Ship& source) {
return (_type == source._type &&
_damagedSquares == source._damagedSquares &&
_orientation == source._orientation && _state == source._state);
}
Run Code Online (Sandbox Code Playgroud)
我也尝试了"朋友"方法,但这也不起作用.类本身的结构如下:
class Ship {
private:
ShipType _type;
int _damagedSquares;
ShipOrientation _orientation;
ShipState _state;
public:
Ship();
Ship(ShipType type);
~Ship();
bool operator==(const Ship& source);
};
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
附加信息:
std::vector<Ship> remainingShips;
MultiArray& squares = opponentGridCopy.GetSquares();
for (RowIterator rowIterator = squares.begin(); rowIterator != squares.end();
++rowIterator) {
for (ColumnIterator columnIterator = rowIterator->begin();
columnIterator != rowIterator->end(); ++columnIterator) {
Square* current = &(*columnIterator);
SquareState currentState = current->GetState();
if (currentState != SquareState::Hit)
current->SetState(SquareState::Vacant);
Ship* potentialShip = current->GetOwner();
if (potentialShip != nullptr) {
int damagedSquares = potentialShip->GetDamagedSquares();
if (!damagedSquares) {
current->SetState(SquareState::Populated);
break;
}
if (remainingShips.empty() ||
std::find(remainingShips.begin(), remainingShips.end(),
potentialShip) ==
remainingShips.end()) // should be *potentialShip
remainingShips.push_back(*potentialShip);
}
}
}
return remainingShips;
Run Code Online (Sandbox Code Playgroud)
我正在将指针作为比较值传递...只需取消引用它并且find()现在可以正常工作.
像这样声明你的比较运算符:
bool Ship::operator==( const Ship &source ) const
Run Code Online (Sandbox Code Playgroud)
请注意尾随const.