Trying to implement operator overloading using the following code:
class Number
{
T value;
public:
Number(T v);
Number();
Number<T> operator (Number<T>&, const Number<T> &);
T getValue() { return value; };
};
template <typename T>
Number<T>::Number(T val):value(val) { }
template <typename T>
Number<T> Number<T>::operator (Number<T>& lhs, const Number<T> & rhs) {
return lhs.value rhs.value;
}
Trying to emulate similar examples found online, but this attempt generates several compiler errors
'{' missing function header (old-style format list?)
binary 'operator ' has too many parameters
class template "Number" has no member "operator "
Number<T> Number<T>::operator (Number<T>& lhs, const Number<T> & rhs)
With all the decisions: whether or not to include "<T>"; whether or not to use references for sends and returns; whether or not to use "const" and/or "friend"; and whether or not to use "this", "new" and/or "->"; it's confusing enough to search for outside help :).
Any idea what (many things) I'm doing wrong?
Thanks for your consideration
CodePudding user response:
You're forgetting about the implicit this parameter that are present as the first parameter in a non-static member function.
To solve your probelm just remove the extra first parameter from operator as shown below:
template<typename T>
class Number
{
T value;
public:
Number(T v);
Number();
Number<T> operator (const Number<T> &);//REMOVED UNNECESSARY PARAMETER
T getValue() { return value; };
};
template <typename T>
Number<T>::Number(T val):value(val) { }
template <typename T>
Number<T> Number<T>::operator (const Number<T> & rhs) { //REMOVED UNNECESSARY PARAMETER
return value rhs.value;//CHANGED lhs.value to value
}
The output of the program can be seen here.
CodePudding user response:
Remove this line:
Number<T> operator (Number<T>&, const Number<T> &);
and define operator out of the class body this way:
template<typename T>
Number<T> operator (Number<T> const& lhs, Number<T> const& rhs) {
auto ret{ lhs };
ret.value = rhs.value;
return ret;
}
