Hi. I've got a problem with this addition operator, that's supposed to concatenate two class objects containing arrays, like so:
c=a+b
where: c.data[15] = a.data[7] + b.data[8]
and: c.size = 15
a.size = 7
b.size = 8
Problem is; my operator adds successfully, but overwrites one of the source classes.
I'm confused as to how you're supposed to utilise two source objects, and then create a 3rd object to hold the result. Can someone please spell it out for me?
This is latest revision, but it creates some sort of cyclical error...
Code:
float_seq &operator+(const float_seq &a)
{
// so create a new object, large enough for both
float_seq temp(number_of_elements+a.number_of_elements);
for(int i=0;i<=(number_of_elements-1);i++) temp.float_seq::write(i,data[i]);
for(int i=0;i<=(a.number_of_elements-1);i++) temp.float_seq::write((i+number_of_elements),a.data[i]);
number_of_elements = number_of_elements+a.number_of_elements;
return (temp);
}
operator + should return a float_seq object - not return a reference to a temporary object as you do in both versions of your code.
The temporary object should not be allocated by new inside the operator function because it will never be deleted. The original version correctly allocates float_seq as a local-scoped variable. Note that a+b implies that a temporary float_seq is created and THEN the operator = (or possibly copy constructor) is applied when assigning to c.
Make sure that you have implemented both the copy constructor and assignment operator (=). For POD classes they are not always necessary, but since your class contains arrays I believe that they are.
These two lines seem to be a big source of trouble:
I'm afraid it still isn't working - when I call the operator the program hangs. When I try to 'cout << X+Y;' for example, there doesn't seem to be a valid value in the number_of_elements field, as it the thing it's trying to print is no longer there.
Can anyone shed some light?
Bookmarks