Can't find error in template class

template< typename T >
double GetAverage(T tArray[], int nElements)
{
    T tSum = T(); // tSum = 0
    for (int nIndex = 0; nIndex < nElements; ++nIndex)
    {
      tSum += tArray[nIndex];
    }
    // convert T to double
    return double(tSum) / nElements;
};

template <typename T>
class pair {
public:
    T a;
    T b;
    pair () {
        a=T(0);
        b=T(0);
    } ;
    pair (T a1, T b1) {
        a=a1;
        b=b1;
    };
    pair operator += (pair other_pair) {
        return pair(a+other_pair.a, b+other_pair.b);
    }

   operator double() {
       return double(a)+ double(b);
    }
};

int main(void)
{
    pair<int > p1[1];
    p1[0]=pair<int >(3,4);
    std::cout<< GetAverage <pair <int >>(p1,1) <<"\n";
}

I can't understand why it prints 0 instead of 3.5.

When I copy code from C++ -- How to overload operator+=? all went fine. But I can't understand where I have made a mistake

Upvotes: 3

Views: 135

Answers (1)

mch
mch

Reputation: 9814

pair operator += (pair other_pair) {
    return pair(a+other_pair.a, b+other_pair.b);
}

should be

pair &operator += (const pair &other_pair) {
    a += other_pair.a;
    b += other_pair.b;
    return *this;
}

You need to modify the members of this and return a reference to *this, instead of a new object. It is also a good idea to pass other_pair as a const reference instead of by value.

Upvotes: 5

Related Questions