These are from Professional C++ by Nicholas A. Solter and Scott J. Kleper
About overloading an operator:
• to make classes behave like built-in types
note: the closer the classes are to built-in types, the easier it will be for clients to use.
• to gain greater control over behavior in your program.
main purpose
• to make things easier for clients of the class.
for example:
1 2 3 4 5 6
|
//Global Operator+
//from Professional C++
aThirdCell = myCell + 4; // Works fine.
aThirdCell = myCell + 5.6; // Works fine.
aThirdCell = 4 + myCell; // FAILS TO COMPILE!
aThirdCell = 5.6 + myCell; // FAILS TO COMPILE!
|
implicit conversion works fine when the SpreadSheetCell object is on the left of the operator, but doesn't work when it's on the right.
There's no way you can get the above code to work with an operator+ method
However, you can get it to work if you replace the in-class operator+ with a global operator+ function that is not tied to any particular object.
The function looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
//how to compile it with operator+
const SpreadsheetCell operator+(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs)
{
SpreadsheetCell newCell;
newCell.set(lhs.mValue + rhs.mValue); // Call set to update mValue and mString.
return (newCell);
}
class SpreadsheetCell
{
public:
// ...
friend const SpreadsheetCell operator+(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
//Omitted for brevity
};
|
//now
aThirdCell = myCell + 4; // Works fine.
aThirdCell = myCell + 5.6; // Works fine.
aThirdCell = 4 + myCell; // Works fine.
aThirdCell = 5.6 + myCell; // Works fine.
Note that the implementation of the global operator+ accesses protected data members of
SpreadsheetCell objects. Therefore, it must be a friend function of the SpreadsheetCell class:
Hope this helps. By the way, the examples above are from Professional C++ by Solter and Kleper. I shared this because it is easy to understand what
operators are.