Re: Problems with + operator, trying to sum multiple objects

  • Follow


david wrote:

> Hi, first of all I am going to past a several parts of code.
> 
> That is my class for now:
> class Aibe {
>      public:
>          Aibe();                                 // veikia
>          Aibe(int arr[], int length);            // veikia
>          Aibe(int item, ...);                    // neveikia
>          ~Aibe();                                // veikia
> 
>          bool issubset(Aibe &other);
>          void toArray(int **arr);                // veikia
>          string toString();                      // veikia
>          int length();                           // veikia
> 
>          ostream & operator << (Aibe &other);    // veikia
>          Aibe & operator = (Aibe &two);            // pending
>          Aibe operator + (Aibe &two);            // veikia ?
>          Aibe operator - (Aibe &other);          // pending
>          Aibe operator * (const Aibe &other);    // pending

The problem is with the signatures of these operators.
operator+, operator- and operator* all return a temporary object, and
C++ does not allow such a temporary to be passed to another
function/operator through a non-const reference.
The fix is quite easy, as none of the operators modifies it right-hand
side, you can just pass the parameter as a const reference.

Additionally, as operator+, operator- and operator* do not modify the
object they are invoked on, they should be made const member-functions
(or ideally, taken out of the class as non-member operators).
   Aibe & operator = (const Aibe &two);
   Aibe operator + (const Aibe &two) const;
   Aibe operator - (const Aibe &other) const;
   Aibe operator * (const Aibe &other) const;

Bart v Ingen Schenau
-- 
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Bart 2/16/2008 3:16:32 PM


0 Replies
75 Views

(page loaded in 0.022 seconds)

12/1/2012 11:25:52 AM


Reply: