STHB STHB - 11 months ago 37
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[]; = new int[cap];
tmp.num = a.num;
tmp.cap = a.cap;

memcpy(,, sizeof(int)*num);

for(int i = 0 ; i < num ; i++)
{[i] =[i] *[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 Source

You need to template Array<int> tmp; as Array<T> tmp;, so that them you memcpy(,, 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++)
{[i] = data[i] *[i];