Reputation:
I've a problem with Operator overloading in C++.
I've defined the following class:
template <class T>
class Array
{
public:
//! Default constructor
Array(int ArraySize = 10);
////! Defualt destructor
Array<T>::~Array();
//! Redefinition of the subscript operator
T& Array<T>::operator[] (int index);
//! Redefinition of the assignment operator
const Array<T>& Array<T>::operator=(const Array<T>&);
//! Redefinition of the unary operator -
Array<T>& operator-(Array<T>& a);
//! Array length
int size;
private:
//! Array pointer
T *ptr;
};
The unary operator - is defined as follow:
//! Redefinition of the unary operator -
template<class T>
Array<T>& operator-(Array<T>& a){
static Array<T> myNewArray(a.size);
for( int i = 0; i < a.size; i++){
myNewArray[i]=-a[i];
}
return myNewArray;
}
How can I avoid the persistence in memory of "myNewArray"? Whitout "static" declaration myNewArray disappears when the function ends and fails any assignment like VectorA=-VectorB.
The second problem is about the overload of casting operator; I've overloaded the casting operator this way:
//!CASTING
template <class B>
operator Array<B>(){
static Array<B> myNewArray(size);
.... a function makes the conversion and returns myNewArray populated...
return myNewArray;
}
But it doesn't work! The object myNewArray seems to disappear after the function execution with the static declaration too. Any assignment like VectorA=(Array<'anytype'>)VectorB fails.
Where is the error? May everybody suggest a solution, please? Thank you in advance!
Upvotes: 0
Views: 988
Reputation:
For your operators don't return a reference. Return a copy of myNewArray. Most compilers can elide the copy and use return value optimization to make performance acceptable.
You should also mark those methods as const as they do not change state.
template<class T>
Array<T> operator-(const Array<T>& a) {
Array<T> myNewArray(a.size);
for( int i = 0; i < a.size; i++){
myNewArray[i]=-a[i];
}
return myNewArray;
}
Upvotes: 1
Reputation: 76418
Hmm, since both problems involve mysterious failures to properly assign new values, is there something wrong in the assignment operator?
Upvotes: -1
Reputation: 76418
Without "static" declaration myNewArray disappears when the function ends and fails any assignment like VectorA=-VectorB.
No, it doesn't. The compiler makes sure it hangs around long enough to get copied.
Also, the code will be a bit cleaner if you initialize myNewArray as a copy of the original:
Array<T> myNewArray(a);
for (int i = 0; i < myNewArray.size(); ++i)
myNewArray[i] *= -1;
Upvotes: 0