Reputation: 27
How do I overload the minus operator accepting the same number of parameters, but having different return types?
Template class:
template <typename T>
T minus (T x, T y) {
return (x - y);
}
template <typename T>
double absMinus (T x, T y) {
double sd = abs(x - y);
return sd;
}
Operator overloading class:
Minus operator-(Minus &p, Minus &q) {
return (p.something - q.something);
}
double operator-(Minus &p, Minus &q) {
return (p.something() - q.something());
}
When I tried to compile, it gave me the following error:
Minus.h:25: error: new declaration ‘double operator-(Minus&, Minus&)’
Minus.h:24: error: ambiguates old declaration ‘Minus operator-(Minus&, Minus&)’
Upvotes: 0
Views: 3058
Reputation: 1263
Operator overloading is just an extension of function/method overloading. For function overloading, the signature of the functions should be different. As reported in your post, the signatures of the two functions are the same.
Please note that function/method signature doesn't include the return type.
Read this for more on this topic here: Java - why no return type based method overloading?
Upvotes: 0
Reputation: 46027
No, you can't. Overloading can be done only when the parameter list is different. For example:
int myFun(int);
double myFun(int);
Now you are calling myFun(10)
. Compiler has no way to determine which version to call.
Upvotes: 2
Reputation: 791869
You cannot, overload resolution chooses an overload based only on the types of function parameters.
Upvotes: 0