Help! Operator + problems

T

Timothy Stark

Hello folks,

I am trying get operator + working. I developed a class for a pair (left
and right values).

class Word10 {
public:
uint18 left, right;

:
:

inline Word10& operator += (const Word10& val)
{
if ((right += val.right) & H10_MASK)
(right &= H10_MASK, left++);
left = (left + val.left) & H10_MASK;
return *this;
}
};

inline Word10& operator + (const Word10& x, const Word10& y)
{ return Word10 (x) += y; }

:
:

Word10 x(2, 2), y(3, 3), z;

z = x + y;

cout << "Z = (" << z.left << "," << z.right << ")" << endl;

I tried to print but it did not work. It crashed with segmentation fault or
incorrect result of sum (scrambled results). However, it works so well with
using += operator. Does anyone have resolve the problem with that? I am
using GCC C/C++ compiler.

Thank you!
Tim
 
J

James Lothian

Timothy said:
Hello folks,

I am trying get operator + working. I developed a class for a pair (left
and right values).

class Word10 {
public:
uint18 left, right;

:
:

inline Word10& operator += (const Word10& val)
{
if ((right += val.right) & H10_MASK)
(right &= H10_MASK, left++);
left = (left + val.left) & H10_MASK;
return *this;
}
};

inline Word10& operator + (const Word10& x, const Word10& y)
{ return Word10 (x) += y; }

:
:

Word10 x(2, 2), y(3, 3), z;

z = x + y;

cout << "Z = (" << z.left << "," << z.right << ")" << endl;

I tried to print but it did not work. It crashed with segmentation fault or
incorrect result of sum (scrambled results). However, it works so well with
using += operator. Does anyone have resolve the problem with that? I am
using GCC C/C++ compiler.

Thank you!
Tim

Those 36-bit machines are a pain, eh? I think the problem is that
operator+ is
returning a reference to a temporary. Removing the & (so that the result
is
returned by value) might be enough.

James
 
R

Ron Natalie

Timothy Stark said:
inline Word10& operator + (const Word10& x, const Word10& y)
{ return Word10 (x) += y; }

operator+ should NOT return a reference. It should return a Word10 object
(by value). Just remove the first & on the line above and things shoud be fine.

The fact that the above even compiles is one of those insidious rvalue to
lvalue conversions. The object returned has ceased to be by the time you
reach the caller of operator+.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top