0

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' ?

2 Answers 2

0

You need to template Array<int> tmp; as Array<T> tmp;, so that then 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 still have loop. Just write:

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

Your function does not have a return type. C++ will therefore default to int. to solve this, make sure the function returns an Array<int> (the type of tmp).

1
  • 1
    I believe it is actually the compiler that does the defaulting, I think the standard prohibits that behaviour(C99 does too, no reason C++ wouldnt), but dont take this as granted
    – Creris
    Nov 11, 2016 at 23:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.