Help on parameters and operators

Hey Community, I am trying to create an operator that take two classes and produces one, but it keeps saying:


person.cpp:128:57: error: ‘Person Person::operator+(const Person&, const Person&)’ must take either zero or one argument


1
2
3
4
5
6
7
8
Person Person::operator+(const Person& A,const Person& B)

{ 

  return Person C(A.fname , B.lname, 0);

  }
You send a message to an object.
When you say c = a+b; you are sending the `assign' (operator=) message to the `c' object
The body of the message is `a+b', that it is sending the message `sum' (operator+) to the object `a'

You wrote Person Person::operator+(const Person& A,const Person& B)
that would be used as useless.operator+(a,b);
¿now why do you want the `useless' object? (hint: you don't, it's useless)

Instead you want to use it like a.operator+(b); or for short a + b;
The you would write
1
2
3
4
5
6
7
8
Person Person::operator+(const Person& B) const{ //as a non-static member function
   return Person(this->fname, b.lname, 0);
}

//or
Person operator+(const Person& A,const Person& B){ //as a non-member function
   return Person(A.fname , B.lname, 0);
}


However, that's not an intuitive way to add people.


The zero parameter refers to when you use it as a sign
like
1
2
reverse = -value;
same = +value;
Zero or one arguments is because it is a member of the Person class.
Try:
1
2
3
4
Person Person::operator+ (const Person& B) const
{
    return Person(this->fname, B.lname, 0);
}


http://en.cppreference.com/w/cpp/language/operators
http://www.cplusplus.com/doc/tutorial/templates/
http://www.cprogramming.com/tutorial/operator_overloading.html

Edit: I would like to add-on to what ne555 said about
1
2
3
Person operator+(const Person& A,const Person& B){ //as a non-member function
   return Person(A.fname , B.lname, 0);
}

To do this you would also need to declare a friend function inside the class.
Last edited on
Topic archived. No new replies allowed.