c++ - Overload += operator for two differents private attributes -


is possible overload += operator 2 differents private attributes in class ?

i'm trying :

const int &test::operator+=(const int &rhs) {    *this = *this + rhs;    return *this; } 

here class :

class test {    private:       int _n;       int _n2;    public:       int getn();       void setn(int n);       int getn2();       void setn2(int n);       const int &operator+=(const int &rhs); } 

i assume want able use += _n , _n2 independently.
note examples not complete. left out initialization , other parts reduce bloating.

1) encapsulate ints

class number { public:     number& operator += (int rhs)     {         _n += rhs;         return *this;     }      int get() const;     void set(int n);  protected:     int _n; };  class test { public:     number& n()     { return _n; }      const number& n() const     { return _n; }      number& n2()     { return _n2; }      const number& n2() const     { return _n2; }  private:     number _n;     number _n2; };  int main() {     test t;     t.n() += 24;  // add _n     t.n2() += 42; // add _n2     return 0; } 

2) use 2 seperate base classes

class n { public:     n& operator += (int rhs)     {         _n += rhs;         return *this;     }      int getn() const;     void setn(int n);  protected:     int _n; };  class n2 { public:     n2& operator += (int rhs)     {         _n2 += rhs;         return *this;     }      int getn2() const;     void setn2(int n);  protected:     int _n2; };  class test     : public n     , public n2 {};  int main() {     test t;      // add _n     t.n::operator += (24);    // explicit operator     static_cast<n&>(t) += 24; // explicit cast      // add _n2     t.n2::operator += (42);    // explicit operator     static_cast<n2&>(t) += 24; // explicit cast      return 0; } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -