Error C2100 - Invalid access

I have a very simple program written to define the * operator in an array template class. When I try to compile, it gives me the error "illegal indirection". Any help on this subject 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 main function of the test:

 cout<<((*intArray1)*5).GetElement(0); cout<<((*intArray1)*5).GetElement(1); cout<<((*intArray1)*5).GetElement(2); 

Any ideas?

+7
source share
2 answers

Do not forget your rules > operator priority . It seems that you want:

 (*TempArray2)[i] 

Otherwise, your expression *TempArray2[i] treated as *(TempArray2[i]) , and I assume that your NumericArray<T> does not have a unary * operator overloaded.

+10
source

In *TempArray2[i] * applies to TempArray[2] due to priority rules, and there is a fair likelihood that array elements do not 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 create objects in C ++ - you probably don't need to use it in main .)

This would be better (and avoid the whole problem of indirection):

 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; } 
+1
source

All Articles