I have a very simple program written to define a * operator in an array template class. When I try to compile it gives me an error "illegal indirection". Any help on the matter would be greatly appreciated!
This is the operator definition:
template <typename T>
NumericArray<T> NumericArray<T>::operator * (const int factor) const
{
NumericArray<T>* TempArray2 = new NumericArray<T>(Size());
for (int i=0; i<Size(); i++)
{
*TempArray2[i] = ((GetElement(i))*(factor));
}
return *TempArray2;
}
And this is the implementation in the test main function:
cout<<((*intArray1)*5).GetElement(0);
cout<<((*intArray1)*5).GetElement(1);
cout<<((*intArray1)*5).GetElement(2);
Any ideas?
Don't forget your operator precedence rules. It seems that you want:
(*TempArray2)[i]
Otherwise your expression *TempArray2[i]
is considered as *(TempArray2[i])
and I suppose your NumericArray<T>
type doesn't have the unary *
operator overloaded.
In *TempArray2[i]
, the *
is applied to TempArray[2]
because of the precedence rules, and there's a fair chance that the array elements don't have a unary *
operator.
But your use of dynamic allocation and then dereferencing to return by value means that you have a memory leak.
(You don't need new
to create objects in C++ - you probably don't need to use it in main
either.)
This would be better (and avoids the whole indirection issue):
template <typename T>
NumericArray<T> NumericArray<T>::operator * (int factor) const
{
NumericArray<T> TempArray(Size());
for (int i = 0; i < Size(); i++)
{
TempArray[i] = GetElement(i) * factor;
}
return TempArray;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With