I’m trying to figure out why this code works (particularly the “price” part)
struct CarType
{
string maker;
int year;
float price;
bool operator > (carType car)
{
if (price > car.price)
return true;
else return false;
}
};
It says “we don’t nees a myCar.price, because myCar was the left operand”. What does that mean? I wrote this in another .h file:
bool operator > (Fraction a, Fraction b)
{
if (a.numerator*b.denominator > b.numerator*a.denominator) return true;
else return false;
}
See how I passed 2 Fraction structs? I’m not sure why the “myCar” only has to pass one CarType data struct or what the explanation means. Can someone please enlighten me? Thanks!
CarTypeis a struct. It contains information about a car. Assuming it has been initialized properly, it has set values formaker,year, andprice.bool operator > (carType car)is a member operator ofCarType. When the member operator>is called, it is called from/by the object on the left, just like a function would be. If you had a function insideCarTypecalledmyFunction, you would call it like this:And it would operate on the data already set up inside
myCar, right? It’s the same with operators. When you create the>operator forCarType, you call it like this:Probably with an if or something surrounding it, but the point stands. Since
myCaris on the left of the>operator, it is the left operand.>is called onmyCar, andotherCaris passed in as the right hand variable. The operators just make things look prettier; in this case, your>function is the same as if you’d written this function insideCarType:And then this function would be called like this:
In this case it’s clear what’s going on, right?
myCaris the object the function is being called on;otherCaris the car it’s being compared against. It’s similar when you use the operator; it’s implied that the left operand is calling the function, and the right operand is passed in. Overloading operators makes code simple and easy to read, and provides flexibility (ie. there are some data structures which would now perform sorts based on your>operator, which they couldn’t do if you decided to define equality with anisGreaterThanfunction.I hope this clears up your confusion; please let me know if there’s anything else you’d like me to explain!