I'm creating a subclass vector and I would like to overload its = operator (originally, it was the + operator), but if I assign the result of it to a reference, it doesn't modify the original object.
It seems I'm missing something about C++ references, but I don't know what it is.
If someone could kindly point me the error, I'd be very grateful.
Here is the code (compiled on Ubuntu 12 with g++)
#include <iostream>
#include <vector>
using namespace std;
class myvector : public vector<long double> {
public:
int n_elements;
myvector(int elems){
n_elements = elems;
reserve(n_elements);
}
myvector(int elems,long double initWith){
n_elements = elems;
reserve(n_elements);
for (int i=0; i<n_elements; i++)
(*this)[i]=initWith;
}
myvector& operator= (const vector<long double>& v){
for(int i = 0; i < n_elements; i++)
(*this)[i]=v[i];
return *this;
}
};
#define SIZE 200
void fill(myvector& m){
myvector temp = myvector(SIZE,1.0);
cout <<"0 "<< temp[0] << endl; // (0) returns 1
m = temp;
cout <<"1 "<< m[0] << endl; // (1) returns 12
}
int main(){
myvector m = myvector(SIZE,12.0);
fill(m);
cout <<"2 "<< m[0] << endl; // (2) returns 12
myvector n = myvector(SIZE,1.0);
cout <<"3 "<< n[0] << endl; // (3) returns 1
}