Task is to overload the operator + so that it adds two arrays. Array is a class with two private members int* data, and int m(capacity of array).
void Array::setM(int m){
this->m = m;
this->data = new int[this->m];
}
int& Array::operator[](int i){
return this->data[i];
}
Array& Array::operator+(Array& a){
Array res;
if (this->m >= a.m) {
res.setM(this->m);
for (int i=0; i<this->m; i++){
res.data[i] = this->data[i] + a.data[i];
}
}
else if (this->m < a.m) {
res.setM(a.m);
for (int i=0; i<a.m; i++){
res.data[i] = this->data[i] + a.data[i];
}
}
Array& rez = res;
return rez;
}
This is main:
int main()
{
Array a(3);
Array& a1 = a;
a1[0] = 1;
a1[1] = 2;
a1[2] = 4;
Array b(3);
Array& b1 = b;
b1[0] = 1;
b1[1] = 2;
b1[2] = 4;
Array& c = a1.operator+(b1);
for (int i=0; i<3; i++){
cout<<c[i]<<" ";
}
return 0;
}
The function works fine when the return type is Array, but when the return type is Array& it returns 173104 4200736 4200896. I am starting with c++ so references confuse me a bit, I do not see a point of function returning the reference type?