我试图弄清楚为什么这段代码有效(特别是“价格”部分)
struct CarType
{
string maker;
int year;
float price;
bool operator > (carType car)
{
if (price > car.price)
return true;
else return false;
}
};
它表示“我们不需要 myCar.price,因为 myCar 是左操作数”。这意味着什么?我在另一个 .h 文件中写了这个:
bool operator > (Fraction a, Fraction b)
{
if (a.numerator*b.denominator > b.numerator*a.denominator) return true;
else return false;
}
看看我是如何传递 2 个 Fraction 结构的?我不确定为什么“myCar”只需要传递一个 CarType 数据结构或解释的含义。有人可以启发我吗?谢谢!
最佳答案
如果您将 operator>
编写为自由函数(不是类的成员),那么您需要两个操作数。
如果你把它写成成员函数,那么你仍然有两个操作数,但其中一个是隐藏的this
操作数。 (请记住,当您调用非静态成员函数时,您是在类的特定实例上调用它。)
它可能会帮助您理解我是否放入隐式 this->
bool operator > (carType car)
{
if (this->price > car.price)
return true;
else return false;
}
这也意味着如果您愿意,您可以像这样比较汽车:
CarType one, two;
if (one.operator>(two)) // same as if (one > two)
{
// some code...
}
关于c++ - 成为左操作数意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12232849/