Salve a tutti .. vediamo se qualcuno riesce a darmi una mano .. non riesco a capire la violazione di memoria che ottengo alla chiamata al distruttore di un obj al quale e` stata assegnato il risultato di un operazione di overloading del operatore +
codice:
#ifndef ARRAY_H
#define ARRAY_H
#include<iostream>
#include<new> // eception for bad_alloc
#include<cstdlib>
using namespace std;
// forward declaration
template<typename T>
class Array ;
template<typename T>
ostream& operator<<( ostream& output, const Array<T>& A) ;
template<typename T>
class Array{
friend ostream& operator<< <T>( ostream& , const Array<T>& );
public:
Array(int = 1, T = 0);
Array( const Array<T> & );
~Array();
// T getElement()const;
// void setElement(int , T);
// void print()const;
const Array &operator+=( const Array &);
const Array operator+( const Array &) const;
private:
int size;
T* arrayPtr;
// utility function
T* allocate( const T& )throw(bad_alloc);
T* allocate( const Array<T>& )throw(bad_alloc);
};
template<typename T>
Array<T>::Array(int element , T value)
:size(element),
arrayPtr(allocate(value))
{ }
template<typename T>
Array<T>::Array( const Array<T> & A)
: size(A.size),
arrayPtr(allocate(A))
{ }
template<typename T>
T* Array<T>::allocate( const T&value ) throw(bad_alloc)
{
T* aPtr ;
try
{
aPtr = new T[size];
// initialization part
for(int i=0 ; i< size ; i++)
{
aPtr[i] = value;
}
}
catch( bad_alloc & unnalocate )
{
cout << unnalocate.what();
}
return aPtr ;
}
template<typename T>
T* Array<T>::allocate( const Array<T>& ToCopy ) throw(bad_alloc)
{
T* aPtr ;
try
{
aPtr = new T[size];
// initialization part
for(int i=0 ; i< size ; i++)
{
aPtr[i] = ToCopy.arrayPtr[i] ;
}
}
catch( bad_alloc & unnalocate )
{
cout << unnalocate.what();
}
return aPtr ;
}
template<typename T >
Array<T>::~Array()
{
cout << "distructor called for array" << endl;
cout << *this ;
delete[] arrayPtr ;
}
template<typename T>
ostream& operator<<( ostream& output, const Array<T>& A)
{
for(int i= 0 ; i < A.size ; i++ )
output << A.arrayPtr[i] << " " ;
cout << endl;
}
template<typename T>
const Array<T>& Array<T>::operator+=( const Array<T> & B)
{
if( B.size != size )
{
cout << "Vector must be to same size" << endl;
exit(1);
}
else
{
for(int i=0 ; i< size ; i++)
{
arrayPtr[i] += B.arrayPtr[i] ;
}
return *this ;
}
}
template<typename T>
const Array<T> Array<T>::operator+( const Array &A) const
{
if( size != A.size)
{ cout << "Vector must be to same size" << endl;
exit(1);
}
else
{
Array<T> Temp(A.size) ;
for(int i=0;i<size;i++)
Temp.arrayPtr[i] = arrayPtr[i] + A.arrayPtr[i];
return Temp;
}
}
#endif
e questo il programma di prova
codice:
#include<iostream>
#include "array.h"
using namespace std;
int main()
{
Array<double> A(5,2.2);
Array<double> B(5,1.1);
cout << A << endl ;
cout << B << endl ;
Array<double> C(5);
C= A+=B ;
cout << C << endl ;
Array<double> D(B);
D = C + B;
cout << "ok " << endl ;
cout << D << endl;
return 0;
}