为什么使用 and 运算符比较 if 语句中的 2 个对象会抛出错误,而使用 2 if 语句则不会

Why does using the and operator to compare 2 objects in an if statement throw an error when using 2 if statements does not

本文关键字:语句 if 出错 错误 对象 and 比较 为什么 运算符      更新时间:2023-10-16

我在我的磁贴类中是一个方法是TileEqual,我正在尝试将私有变量的形状和颜色与另一个磁贴类进行比较。当我使用 and 运算符 Visual Studio 代码使用当前行时,出现错误"表达式必须是可修改的值">

当我嵌套下面注释掉的 if 语句时,我没有收到任何错误。

bool Tile::isTileEqual(Tile tile) {
Colour colour = tile.getColour();
Shape shape = tile.getShape();
if(this->shape == shape && this->colour = colour) {
//if(this->colour == colour) {
return true;
//}
}
return false;
}

如果 2 个磁贴具有相同的属性,则预期结果将为真。 如果它们不同,则为 false。

在使用&&的那个上,你只有一个=。 对于单个=它是一个作业,您想进行比较。

应该是:

if(this->shape == shape && this->colour == colour) {

我还建议您直接返回表达式的值:

return this->shape == shape && this->colour == colour;

if (x) return true; else return false;...被认为是丑陋/不良做法。