Overload + =运算符,用于两个不同的私有属性

时间:2015-04-25 10:02:24

标签: c++

是否可以为类中的两个不同私有属性重载+ =运算符?

我试图做这样的事情:

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

这是我的班级:

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);
}

1 个答案:

答案 0 :(得分:1)

我假设您希望能够+=_n独立使用_n2
请注意,我的示例并不完整。我遗漏了初始化和其他部分以减少膨胀。

1)封装您的int

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 to _n
    t.n2() += 42; // add to _n2
    return 0;
}

2)使用两个单独的基类

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 to _n
    t.N::operator += (24);    // explicit operator
    static_cast<N&>(t) += 24; // explicit cast

    // add to _n2
    t.N2::operator += (42);    // explicit operator
    static_cast<N2&>(t) += 24; // explicit cast

    return 0;
}