0
struct Vec{
    int x;
    int y;
    Vec operator+(const Vec &v){
        x+=v.x;     y+=v.y;
        return *this;
    }
    Vec Vec::operator+=(const Vec &v){
        x+=v.x;     y+=v.y;
        return *this;
    }
};
ostream& operator<<(ostream &out, const Vec &v){
    return out << "x : " << v.x << "\ny : " << v.y << "\n";
}

my + and += operator have same behavior how can I avoid redefinition?

g0x0
  • 93
  • 7
  • See the *Binary arithmetic operators* section of the top answer. – NathanOliver Oct 06 '21 at 14:22
  • 2
    `operator+=` should be returning a reference to `this`, i.e. `Vec&`, not a brand new `Vec`. – PaulMcKenzie Oct 06 '21 at 14:22
  • @PaulMcKenzie: For that matter, `operator+` should be `const`, i.e. shouldn't be modifying `this` (it's returning a copy, but it's a copy of the mutated original object). – ShadowRanger Oct 06 '21 at 14:23
  • You cannot avoid defining both functions. You can call a common implementation function from both to reduce duplication. As for the signature of +=, check out this answer: https://stackoverflow.com/questions/4581961/c-how-to-overload-operator – Gonen I Oct 06 '21 at 14:25
  • @GonenI: Typically, the "common implementation function" *is* `operator+=`, where `operator+` is implemented in terms of it (as NathanOliver mentioned, it's under *Binary arithmetic operators* on [this answer to the duplicate](https://stackoverflow.com/a/4421719/364696)), you don't implement a third function at all (unless perhaps you're in a situation where that third function could form the common implementation for 3+ the mathematical operators by having many operator overloads call it with the `` functors (e.g. `std::plus`, `std::minus`, etc.). – ShadowRanger Oct 06 '21 at 21:05

0 Answers0