Rachel
Rachel

Reputation: 1

C++ operator overload for variables inside class

I would like to implement the + sign to add the my_Contents (int) of two class Mailbox's 'left' and 'right'.

ex.

Mailbox(test);
Mailbox(left); 
Mailbox(right);
left.setSize( 10 ); //my_contents=10
right.setSize( 10 );//"" "" = 5
test.setSize( 5 );// "" ""=5
test = left + right;

However, class Mailbox is NOT initialized as Mailbox 'Name' (my_contents). Therefore my code below will not run. So how would I implement the operator '+' to apply to contents inside the class, which aren't used for initialization, as I am used to?

Mailbox operator +(const Mailbox& left,
              const Mailbox& right) {
Mailbox t =Mailbox( left.my_Contents + right.my_Contents );
return( t );
}

Upvotes: 0

Views: 1116

Answers (2)

Logicrat
Logicrat

Reputation: 4468

This seems to accomplish what you are looking for:

class Mailbox
{
public:
  Mailbox() {}
  Mailbox(int x) : my_contents(x) {}
  void SetSize(int x) 
  {
    my_contents = x;
  }
  int my_contents;
};

static Mailbox operator+(Mailbox& left, Mailbox& right)
{
  return Mailbox(left.my_contents + right.my_contents);
}

Mailbox test;
Mailbox left(10);
Mailbox right(5);
test = left + right;

And it does compile with the proper surroundings.

Upvotes: 0

user93353
user93353

Reputation: 14039

1) Call the setSize to set my_Contents of the result.

Mailbox operator +(const Mailbox& left, const Mailbox& right) 
{
    int s = left.my_Contents + right.my_Contents;
    Mailbox t;
    t.setSize(s);
    return t;
}

Another thing is that your operator needs to be a friend of class Mailbox

i.e.

class Mailbox
{
    int my_contents;

    public:
    void setSize(int x) ;

    // Whatever else

    friend Mailbox operator +(const Mailbox& left, const Mailbox& right);
};

2) or if you don't want to make it a friend you, have a getSize method

Mailbox operator +(const Mailbox& left, const Mailbox& right) 
{
    int s = left.getSize() + right.getSize();
    Mailbox t;
    t.setSize(s);
    return t;
}

where getSize is a member method

void getSize()
{
    return my_Contents;
}

3) Or you could implement it in terms of +=

class Mailbox
{
    int my_Contents;
    public:

    Mailbox & operator +=(const Mailbox & r)
    {
        my_Contents += r.my_Contents;
        return *this;
    }
    // Whatever else

};

Mailbox operator +(const Mailbox& left, const Mailbox& right) 
{
    Mailbox t = left;
    t += right;
    return t;
}

Upvotes: 1

Related Questions