I am looking to overload, let’s say, the addition operator and have it add two objects of the same class. When I declare this “operator+” prototype function in the class declaration in the header file, I pass in both objects as parameters. I get a compiler error saying that “binary ‘operator +’ has too many parameters”. I was searching around for an answer online and found out that declaring an inline function just outside the class declaration in the header file compiled out. I’m wondering what I was doing wrong or if I’m missing something here. Here is the code I am using in the header file.
class Person
{
private:
int age;
double weight;
public:
Person::Person(); //default constructor
Person::~Person(); //default desctructor
Person operator+(Person r, Person i);
};
This compiles with the error I mentioned above. Below is the code that compiles fine.
class Person
{
private:
int age;
double weight;
public:
Person::Person(); //default constructor
Person::~Person(); //default desctructor
};
inline Person operator+(Person r, Person i)
{
return Person(0,0);
}
If you declare
oparator+as an instance function then the first argument is being passed asthisobject and thus you need only one more argument. Read this for more info, in particular try to understand theconstconcept:http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
The best approach as advised in the referenced artice is:
if you decide to use
constversion remember that you will only be able to callconstmethods onthisandireferences. This is the preferred way.The article I referenced to explains the idea of overloading
+=first and then defining+using+=in more details. This is a good idea since+=operator must be separately overloaded.Additionally – David Rodríguez suggests
operator+to be implemented as a free function regardless of the presence of += .