parent nodes: CPlusPlusApuntesC

Plantillas Templates

Como crear un array para enteros y reales al mismo tiempo

Author: César TM
Date: Oct/2009
// File ArrayDin.h
template< class T >
class ArrayDin 
{
    private:
        T *  theElement; // it's a pointer to a element of T type
        long theSize; 
    
	public:
        ArrayDin( long aSize );			 	    // argument constructor
        ArrayDin( const ArrayDin< T > & rhs );	// copy constructor
        ~ArrayDin ();							// destructor
        
		inline long getSize( void ) const;
		inline T    getElementAt( long position ) const;
        inline void putElementAt( long pos, const T &element );
};


// constructor
template< class T >
ArrayDin<T>::ArrayDin( long aSize )
{
    theSize = aSize;
    theElement = new T[ theSize ];
}

// copy constructor
template< class T > 
ArrayDin<T>::ArrayDin( const ArrayDin< T > & rhs )
{
    if( rhs != this )
    {
        theSize = rhs->getSize();
		theElement = new T[ theSize ];
        for( register int c = 0; c < theSize; ++c ) 
			theElement[ c ] = rhs->getElementAt( c );
    }
}


template< class T >
ArrayDin<T>::~ArrayDin( void )
{
    delete  theElement;
}


template< class T > inline T 
ArrayDin<T>::getElementAt( long position ) const
{ 
	return theElement[ position ]; 
}

template< class T > inline void 
ArrayDin<T>::putElementAt( long position, const T & aElement ) 
{ 
	theElement[ position ] = aElement; 
}


template< class T > inline long 
ArrayDin<T>::getSize( void ) const
{
	return theSize;
}
El fichero main para comprobación de la clase array es el siguiente:
// Patrones.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "ArrayDin.h"

int main(int argc, char* argv[])
{
	const int tamanio = 10;

	// *********************************
	// array of integers
	// *********************************
	cout << "Array of integers\n";

	// creation 
	ArrayDin< int > intArray( tamanio );

	// insert elements
	for( register int i = 0; i < tamanio; ++i )
		intArray.putElementAt( i, ( i * 2 ) );

	// read elements
	for( register int j = 0; j < tamanio; ++j )
		cout << intArray.getElementAt( j ) << " ";
	

	// *********************************
	// array of doubles
	// *********************************
	cout << "\n\nArray of doubles\n";

	// creation 
	ArrayDin< double > dblArray( tamanio );

	// insert elements
	for( register int k = 0; k < tamanio; ++k )
		dblArray.putElementAt( k, ( k * 2.1 ) );

	// read elements
	for( register int m = 0; m < tamanio; ++m )
		cout << dblArray.getElementAt( m ) << " ";

	
	cout << endl << endl;
	
	return 0;
}








_________________________________________________________________________________________________________
CPlusPlusApuntesC [camelCaseWordsEnabled: false]