For example, we have this class:
class my_class
{
public:
friend my_class operator* (const my_class&, int a);
friend my_class operator* (int a, my_class&);
};
my_class operator* (int a, my_class&)
{
// do my_class * a
}
my_class operator* (int a, my_class&)
{
// do a * my_class
}
is it possible to do just one operator* to do what these two do?
Thanks!
You cannot do that. However, you can implement one and simply call it from the other one:
my_class operator *(const my_class &l, int r) {
// implement the actual operator here.
}
my_class operator *(int l, const my_class &r) {
return r * l;
}
(Note that you cannot implement the latter function as part of the class. You have to do it externally. The first function can be implemented as an instance method, because its first argument is of the class type.)
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