STHB STHB - 27 days ago 4
C++ Question

Overloading a multiplication operator in a template class array

I'm trying to code a template class for making arrays that has an overloaded multiplication operator. The actual insides of the template class appear fine, however I am having trouble with the overloading of the * operator. I originally had an overloaded operator for multiplying arrays in a regular class, here I am using that first overloaded operator as a base for the template.

This is whats in my header file :

operator * (const Array<T>& a) const; //* operator


And this is whats in my main file :

template <class T>
Array<T>::operator * (const Array<T>& a) const
{
if (num != a.num)
{
cout << "Error, arrays not equal!" << endl;
}

Array<int> tmp;
delete[] tmp.data;

tmp.data = new int[cap];
tmp.num = a.num;
tmp.cap = a.cap;

memcpy(tmp.data, a.data, sizeof(int)*num);


for(int i = 0 ; i < num ; i++)
{
tmp.data[i] = tmp.data[i] * a.data[i];
}

return tmp;
}


The error I am receiving is telling me that something is wrong with tmp. It states "error: cannot convert 'Array' to 'int' in return" in reference to "return tmp" at the end of the function.

I am trying to multiply two arrays (a and c) created in main()

Array <int> d = a * c;


There are error messages relating to Array d, but those also appear to be rooted in the error inside the overloaded operator function. How is tmp being turned into 'int' ?

Answer

You need to template Array<int> tmp; as Array<T> tmp;, so that them you memcpy(tmp.data, a.data, sizeof(int)*num); the size of memory area would realy be same. Also, as @Thecocatrice mentioned, add retutn type to you overloaded operator. This will look like

template<typename T>
Array<T> Array<T>::operator *(const Array<T> &a) { ... };

And last. You dont actually need that memcpy. It doesnt make any sence, since you stil have loop. Just write:

for(int i = 0 ; i < num ; i++)
{
    tmp.data[i] = data[i] * a.data[i];
}