class MyClass;
int main()
{
float a = 5;
MyClass c1;
MyClass c2 = a*c1;
MyClass c3 = c1*a;
}
How can I overload the multiply operator so that both a*c1 and c1*a work?
No, it is not possible. C does not support operator overloading by the developer.
Overloading Binary Operators Suppose that we wish to overload the binary operator == to compare two Point objects. We could do it as a member function or non-member function. To overload as a member function, the declaration is as follows: class Point { public: bool operator==(const Point & rhs) const; // p1.
This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.
An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator. Overloaded operators are distinct from overloaded functions, but like overloaded functions, they are distinguished by the number and types of operands used with the operator.
Like so:
MyClass operator* (float x, const MyClass& y)
{
//...
}
MyClass operator* (const MyClass& y, float x)
{
//...
}
The second one can also be a member function:
class MyClass
{
//...
MyClass operator* (float x);
};
The first 2 options work as declarations outside of class scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With