Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"binary 'operator+' has too many parameters

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?)

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • 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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading