Trying to overload + operator
Posted
by
FrostyStraw
on Stack Overflow
See other posts from Stack Overflow
or by FrostyStraw
Published on 2013-10-25T02:08:27Z
Indexed on
2013/10/25
3:54 UTC
Read the original article
Hit count: 128
c++
I cannot for the life of me understand why this is not working. I am so confused. I have a class Person which has a data member age, and I just want to add two people so that it adds the ages. I don't know why this is so hard, but I'm looking for examples and I feel like everyone does something different, and for some reason NONE of them work. Sometimes the examples I see have two parameters, sometimes they only have one, sometimes the parameters are references to the object, sometimes they're not, sometimes they return an int, sometimes they return a Person object. Like..what is the most normal way to do it?
class Person {
public:
int age;
//std::string haircolor = "brown";
//std::string ID = "23432598";
Person(): age(19) {}
Person operator+(Person&) { }
};
Person operator+(Person &obj1, Person &obj2){
Person sum = obj1;
sum += obj2;
return sum;
}
I really feel like overloading a + operator should seriously be the easiest thing in the world except I DON'T KNOW WHAT I AM DOING. I don't know if I'm supposed to create the overload function inside the class, outside, if it makes a difference, why if I do it inside it only allows one parameter, I just honestly don't get it.
© Stack Overflow or respective owner