domingo, 22 de febrero de 2015

Operator Visual C++



#include <iostream>
#include <cstdlib>

using namespace std;

class DArray
{
public:

 DArray( int nLengthOfArray = 0 ) : nLength( nLengthOfArray ) , pArray( nullptr )
 {
  cout << "Creando el tamaño de DArray = " << nLength << endl;

  if( nLength > 0 )
  {
   pArray = new int[ nLength ];
  }
 }

 DArray( DArray &da )
 {
  cout << "Copiando el tamaño de DArray = " << da.nLength << endl;
  copyDArray( da );
 }

 ~DArray()
 {
  deleteDArray();
 }

 //opearador de asignacion
 DArray &operator = ( const DArray &s )
 {
  cout << "Asignando el tamaño fuente = " << s.nLength
    << " al tamaño objetivo: " << this -> nLength << endl;

  //elimina las siguientes cosas
  deleteDArray();
  copyDArray( s );

  //regresa la referencia del objeto
  return *this;
 }

 int &operator[]( int index )
 {
  return pArray[ index ];
 }

 int size()
 {
  return nLength;
 }

 void display( ostream &out )
 {
  if( nLength > 0 )
  {
   out << pArray[ 0 ];

   for( int i = 1 ; i < nLength ; i++ )
   {
    out << " , " << pArray[ i ];
   }
  }
 }

protected:

 void copyDArray( const DArray &da );
 void deleteDArray();

 int nLength;
 int *pArray;
};

void DArray :: copyDArray( const DArray &source )
{
 nLength = source.nLength;
 pArray = nullptr;

 if( nLength > 0 )
 {
  pArray = new int[ nLength ];

  for( int i = 0 ; i < nLength ; i++ )
  {
   pArray[ i ] = source.pArray[ i ];
  }
 }
}

void DArray :: deleteDArray()
{
 nLength = 0;
 delete pArray;
 pArray = nullptr;
}

int main( int argc , char *argv[] )
{
 DArray da1( 5 );

 for( int i = 0 ; i < da1.size() ; i++ )
 {
  da1[ i ] = i;
 }

 cout << "da1 = "; 
 da1.display( cout );
 cout << endl;

 DArray da2 = da1;

 da2[ 2 ] = 20;

 cout << "da2 = ";
 da2.display( cout );
 cout << endl;

 da2 = da1;
 cout << "da2 = ";
 da2.display( cout );
 cout << endl;

 system("pause");
 return 0;
}


No hay comentarios:

Publicar un comentario