Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,261 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,559 people online right now. Registration is fast and FREE... Join Now!




Template Class

 
Reply to this topicStart new topic

Template Class, Create an array of Rational Class

ToLost
12 Dec, 2006 - 06:20 PM
Post #1

New D.I.C Head
*

Joined: 10 Dec, 2006
Posts: 4


My Contributions
I have created a template class Array.
What i need help with is how do i use my ratational class and array class to work to gogather so that i can create an array of rational classes?
CODE

CODE - for array.h
// Fig. 11.6: Array.h
// Array class for storing arrays of integers.
#ifndef ARRAY_H
#define ARRAY_H

#include <iostream>
#include <stdexcept>
using namespace std;


template <class T>
class Array
{
   friend ostream &operator<< <T>( ostream &, const Array<T> & );
   friend istream &operator>>( istream &, Array<T> & );
public:

    Array( int = 10 ); //throw (std::bad_alloc) default constructor
   Array( const Array<T> & ); // copy constructor
   ~Array(); // destructor
   int getSize() const; // return size

   const Array<T> &operator=( const Array<T> & ); // assignment operator
   bool operator==( const Array<T> & ) const; // throw (std::bad_alloc)equality operator

   // inequality operator; returns opposite of == operator
   bool operator!=( const Array<T> &right ) const  
   {
      return ! ( *this == right ); // invokes Array::operator==
   } // end function operator!=
  
   // subscript operator for non-const objects returns modifiable lvalue
   T &operator[]( int );              

   // subscript operator for const objects returns rvalue
   T operator[]( int ) const;  
private:
   int size; // pointer-based array size
   T *ptr; // pointer to first element of pointer-based array
}; // end class Array

// Fig 11.7: Array.cpp
// Member-function definitions for class Array
#include <iostream>
#include <string>
using std::cerr;
using std::cout;
using std::cin;
using std::endl;

#include <iomanip>
using std::setw;

#include <cstdlib> // exit function prototype
using std::exit;

#include "Array.h" // Array class definition

// default constructor for class Array (default size 10)
template <class T>
Array<T>::Array( int arraySize )throw (std::bad_alloc)
{
   try
   {
       if (arraySize > 0)
       {
            size = ( arraySize > 0 ? arraySize : 10 ); // validate arraySize
            ptr = new T [ size ]; // create space for pointer-based array
            for ( int i = 0; i < size; i++ )
            ptr[ i ] = '\0'; // set pointer-based array element
       }
       else
       {
          cout << arraySize<< " is an illegal length for an array"<< endl;
           throw new negitveError;
       }
   }
       catch (negitveError* p)
       {
    
        }


} // end Array default constructor

// copy constructor for class Array;
// must receive a reference to prevent infinite recursion
template <class T>
Array<T>::Array( const Array<T> &arrayToCopy )
   : size( arrayToCopy.size )
{
   ptr = new T[ size ]; // create space for pointer-based array

   for ( int i = 0; i < size; i++ )
      ptr[ i ] = arrayToCopy.ptr[ i ]; // copy into object
} // end Array copy constructor

// destructor for class Array
template <class T>
Array<T>::~Array()
{
   delete [] ptr; // release pointer-based array space
} // end destructor

// return number of elements of Array
template <class T>
int Array<T>::getSize() const
{
   return size; // number of elements in Array
} // end function getSize

// overloaded assignment operator;
// const return avoids: ( a1 = a2 ) = a3
template <class T>
const Array<T> &Array<T>::operator=( const Array<T> &right )
{
   if ( &right != this ) // avoid self-assignment
   {
      // for Arrays of different sizes, deallocate original
      // left-side array, then allocate new left-side array
      if ( size != right.size )
      {
         delete [] ptr; // release space
         size = right.size; // resize this object
         ptr = new T[ size ]; // create space for array copy
      } // end inner if

      for ( int i = 0; i < size; i++ )
         ptr[ i ] = right.ptr[ i ]; // copy array into object
   } // end outer if

   return *this; // enables x = y = z, for example
} // end function operator=

// determine if two Arrays are equal and
// return true, otherwise return false
template <class T>
bool Array<T>::operator==( const Array<T> &right ) const
{
   if ( size != right.size )
      return false; // arrays of different number of elements

   for ( int i = 0; i < size; i++ )
      if ( ptr[ i ] != right.ptr[ i ] )
         return false; // Array contents are not equal

   return true; // Arrays are equal
} // end function operator==

// overloaded subscript operator for non-const Arrays;
// reference return creates a modifiable lvalue
template <class T>
T &Array<T>::operator[]( int subscript )
{
  try
  { // check for subscript out-of-range error
        if ( subscript < 0 || subscript >= size )
        {
            cerr << "\nError: Subscript " << subscript
                << " out of range" << endl;
            //exit( 1 ); // terminate program; subscript out of range
            throw new MyException;
        }
   }
  
   catch (MyException* p) {
    
   }
// end if

   return ptr[ subscript ]; // reference return
} // end function operator[]

// overloaded subscript operator for const Arrays
// const reference return creates an rvalue
template <class T>
T Array<T>::operator[]( int subscript ) const
{
   // check for subscript out-of-range error
   if ( subscript < 0 || subscript >= size )
   {
      cerr << "\nError: Subscript " << subscript
         << " out of range" << endl;
      throw MyException;

     //exit( 1 ); // terminate program; subscript out of range
   }
   catch (MyException* p)
   {
    
   }// end if

   return ptr[ subscript ]; // returns copy of this element
} // end function operator[]

// overloaded input operator for class Array;
// inputs values for entire Array
template <class T>
istream &operator>>( istream &input, Array<T> &a )
{
   for ( int i = 0; i < a.size; i++ )
      input >> a.ptr[ i ];

   return input; // enables cin >> x >> y;
} // end function

// overloaded output operator for class Array
template <class T>
ostream &operator<<( ostream &output, const Array<T> &a )
{
   int i;

   // output private ptr-based array
   for ( i = 0; i < a.size; i++ )
   {
      output << setw( 12 ) << a.ptr[ i ];

      if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output
         output << endl;
   } // end for

   if ( i % 4 != 0 ) // end last line of output
      output << endl;

   return output; // enables cout << x << y;
} // end function operator<<

#include <stdexcept>

class MyException : public std::runtime_error
{
public:
   MyException() : std::runtime_error("MyException") { }
};
  class negitveError : public std::runtime_error
{
public:
   negitveError() : std::runtime_error("NegitiveValue") { }
};
#endif

CODE for rational class
#include <iostream>

using namespace std;


class Rational
{
// see below class for << operator overload
public:
    Rational( int num = 1, int dem = 1 );
    Rational( const Rational & fract );
    ~Rational();

    void setFraction( int num, int dem );
    void setFraction( const Rational & fract );

    inline int getDenominator() const;
        
    inline int getNumerator() const;

    Rational getFraction() const;
    double getDecimal() const;

    Rational operator + ( const Rational & fract ) const;
    Rational operator - ( const Rational & fract ) const;
    Rational operator * ( const Rational & fract ) const;
    Rational operator / ( const Rational & fract ) const;

    bool operator <  ( const Rational & fract ) const;
    bool operator <= ( const Rational & fract ) const;
    bool operator >  ( const Rational & fract ) const;
    bool operator >= ( const Rational & fract ) const;
    bool operator == ( const Rational & fract ) const;
    bool operator != ( const Rational & fract ) const;

    const Rational &operator = ( const Rational & fract );

    const Rational &operator += ( const Rational & fract );
    const Rational &operator *= ( const Rational & fract );
    const Rational &operator /= ( const Rational & fract );
    const Rational &operator -= ( const Rational & fract );

    Rational &operator++ ();
    Rational operator++ ( int );

private:
    int * values;
    static const int NUMER;
    static const int DENOM;
    static const int LEN;

    void reduce();
    inline void resetContainer();

    Rational commonDenom( const int val ) const;
};

ostream &operator << ( ostream &, const Rational & );

CODE FOR MAIN
#include <iostream>
#include <string>
#include <fstream>
#include <iostream>
#include <iomanip>
using std::string;
using std::ifstream;
using namespace std;
#include "Array.h"

int main()
{
    

ifstream fp_in("TopicIin.txt", ios::in);


        int str;
        
        fstream file_op("TopicIin.txt",ios::in);
        char fileName[80];
        while(file_op.good() == false)
        {
        file_op.clear();   // clear error condition
        cout << "Unable to open file. Enter a new name: ";
        cin >> fileName;
        file_op.open(fileName);
        }



Array <int> integers1 (7);

Array <int> integers2 (10);



cout <<"Create double array with default length"<<endl;
Array <double> doublearray(10);
cout <<"Create string array of length 5"<<endl;
Array <string> stringarray(5);
        
cout <<"Create an array of 3 Rational objects"<<endl;
cout <<"Display Rational array:"<<endl;



file_op.close();  // close the streams
    cout << "\n\nPress Enter to end  ";
    cin.ignore();

    
    return 0;
}

User is offlineProfile CardPM
+Quote Post

horace
RE: Template Class
13 Dec, 2006 - 12:16 AM
Post #2

D.I.C Addict
Group Icon

Joined: 25 Oct, 2006
Posts: 573



Thanked: 4 times
Dream Kudos: 50
My Contributions
you had a few errors, this now compiles (all code in a single file) using gcc and starts to run
CODE


    
// Fig. 11.6: Array.h
// Array class for storing arrays of integers.
#ifndef ARRAY_H
#define ARRAY_H

#include <iostream>
#include <stdexcept>
using namespace std;

#include <stdexcept>

class MyException : public std::runtime_error
{
public:
MyException() : std::runtime_error("MyException") { }
};
class negitveError : public std::runtime_error
{
public:
negitveError() : std::runtime_error("NegitiveValue") { }
};

template <class T>
class Array
{
public:
// friend ostream &operator<<( ostream &, const Array<T> & );
// friend istream &operator>> ( istream &, Array<T> & ); // ** <T>

Array<T>( int = 10 ) throw (std::bad_alloc); // remove commentdefault constructor
Array<T>( const Array<T> & ); // copy constructor
~Array<T>(); // destructor
int getSize() const; // return size

const Array<T> &operator=( const Array<T> & ); // assignment operator
bool operator==( const Array<T> & ) const; // throw (std::bad_alloc)equality operator

// inequality operator; returns opposite of == operator
bool operator!=( const Array<T> &right ) const
{
return ! ( *this == right ); // invokes Array::operator==
} // end function operator!=

// subscript operator for non-const objects returns modifiable lvalue
T &operator[]( int );

// subscript operator for const objects returns rvalue
T operator[]( int ) const;
private:
int size; // pointer-based array size
T *ptr; // pointer to first element of pointer-based array
}; // end class Array

// Fig 11.7: Array.cpp
// Member-function definitions for class Array
#include <iostream>
#include <string>
using std::cerr;
using std::cout;
using std::cin;
using std::endl;

#include <iomanip>
using std::setw;

#include <cstdlib> // exit function prototype
using std::exit;

//#include "Array.h" // Array class definition

// default constructor for class Array (default size 10)
template <class T>
Array<T>::Array<T>( int arraySize )throw (std::bad_alloc)
{
try
{
if (arraySize > 0)
{
size = ( arraySize > 0 ? arraySize : 10 ); // validate arraySize
ptr = new T [ size ]; // create space for pointer-based array
for ( int i = 0; i < size; i++ )
ptr[ i ] = '\0'; // set pointer-based array element
}
else
{
cout << arraySize<< " is an illegal length for an array"<< endl;
throw new negitveError;
}
}
catch (negitveError* p)
{

}


} // end Array default constructor

// copy constructor for class Array;
// must receive a reference to prevent infinite recursion
template <class T>
Array<T>::Array<T>( const Array<T> &arrayToCopy )
: size( arrayToCopy.size )
{
ptr = new T[ size ]; // create space for pointer-based array

for ( int i = 0; i < size; i++ )
ptr[ i ] = arrayToCopy.ptr[ i ]; // copy into object
} // end Array copy constructor

// destructor for class Array
template <class T>
Array<T>::~Array()
{
delete [] ptr; // release pointer-based array space
} // end destructor

// return number of elements of Array
template <class T>
int Array<T>::getSize() const
{
return size; // number of elements in Array
} // end function getSize

// overloaded assignment operator;
// const return avoids: ( a1 = a2 ) = a3
template <class T>
const Array<T> &Array<T>::operator=( const Array<T> &right )
{
if ( &right != this ) // avoid self-assignment
{
// for Arrays of different sizes, deallocate original
// left-side array, then allocate new left-side array
if ( size != right.size )
{
delete [] ptr; // release space
size = right.size; // resize this object
ptr = new T[ size ]; // create space for array copy
} // end inner if

for ( int i = 0; i < size; i++ )
ptr[ i ] = right.ptr[ i ]; // copy array into object
} // end outer if

return *this; // enables x = y = z, for example
} // end function operator=

// determine if two Arrays are equal and
// return true, otherwise return false
template <class T>
bool Array<T>::operator==( const Array<T> &right ) const
{
if ( size != right.size )
return false; // arrays of different number of elements

for ( int i = 0; i < size; i++ )
if ( ptr[ i ] != right.ptr[ i ] )
return false; // Array contents are not equal

return true; // Arrays are equal
} // end function operator==

// overloaded subscript operator for non-const Arrays;
// reference return creates a modifiable lvalue
template <class T>
T &Array<T>::operator[]( int subscript )
{
try
{ // check for subscript out-of-range error
if ( subscript < 0 || subscript >= size )
{
cerr << "\nError: Subscript " << subscript
<< " out of range" << endl;
//exit( 1 ); // terminate program; subscript out of range
throw new MyException;
}
}

catch (MyException* p) {

}
// end if

return ptr[ subscript ]; // reference return
} // end function operator[]

// overloaded subscript operator for const Arrays
// const reference return creates an rvalue
template <class T>
T Array<T>::operator[]( int subscript ) const
{
try
   {
   // check for subscript out-of-range error
   if ( subscript < 0 || subscript >= size )
    {
    cerr << "\nError: Subscript " << subscript
    << " out of range" << endl;
    throw MyException("Error: Subscript");

     //exit( 1 ); // terminate program; subscript out of range
    }
}
catch (MyException* p)
{

}// end if

return ptr[ subscript ]; // returns copy of this element
} // end function operator[]

// overloaded input operator for class Array;
// inputs values for entire Array
template <class T>
istream &operator>>( istream &input, Array<T> &a )
{
for ( int i = 0; i < a.size; i++ )
input >> a.ptr[ i ];

return input; // enables cin >> x >> y;
} // end function

// overloaded output operator for class Array
template <class T>
ostream &operator<< ( ostream &output, const Array<T> &a )
{
int i;

// output private ptr-based array
for ( i = 0; i < a.size; i++ )
{
output << setw( 12 ) << a.ptr[ i ];

if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output
output << endl;
} // end for

if ( i % 4 != 0 ) // end last line of output
output << endl;

return output; // enables cout << x << y;
} // end function operator<<


#endif

//CODE for rational class
#include <iostream>

using namespace std;


class Rational
{
// see below class for << operator overload
public:
Rational( int num = 1, int dem = 1 );
Rational( const Rational & fract );
~Rational();

void setFraction( int num, int dem );
void setFraction( const Rational & fract );

inline int getDenominator() const;

inline int getNumerator() const;

Rational getFraction() const;
double getDecimal() const;

Rational operator + ( const Rational & fract ) const;
Rational operator - ( const Rational & fract ) const;
Rational operator * ( const Rational & fract ) const;
Rational operator / ( const Rational & fract ) const;

bool operator < ( const Rational & fract ) const;
bool operator <= ( const Rational & fract ) const;
bool operator > ( const Rational & fract ) const;
bool operator >= ( const Rational & fract ) const;
bool operator == ( const Rational & fract ) const;
bool operator != ( const Rational & fract ) const;

const Rational &operator = ( const Rational & fract );

const Rational &operator += ( const Rational & fract );
const Rational &operator *= ( const Rational & fract );
const Rational &operator /= ( const Rational & fract );
const Rational &operator -= ( const Rational & fract );

Rational &operator++ ();
Rational operator++ ( int );

private:
int * values;
static const int NUMER;
static const int DENOM;
static const int LEN;

void reduce();
inline void resetContainer();

Rational commonDenom( const int val ) const;
};

ostream &operator << ( ostream &, const Rational & );

//CODE FOR MAIN
#include <iostream>
#include <string>
#include <fstream>
#include <iostream>
#include <iomanip>
using std::string;
using std::ifstream;
using namespace std;
//#include "Array.h"

int main()
{


ifstream fp_in("TopicIin.txt", ios::in);


int str;

fstream file_op("TopicIin.txt",ios::in);
char fileName[80];
while(file_op.good() == false)
{
file_op.clear(); // clear error condition
cout << "Unable to open file. Enter a new name: ";
cin >> fileName;
file_op.open(fileName);
}



Array <int> integers1 (7);

Array <int> integers2 (10);



cout <<"Create double array with default length"<<endl;
Array <double> doublearray(10);
cout <<"Create string array of length 5"<<endl;
Array <string> stringarray(5);

cout <<"Create an array of 3 Rational objects"<<endl;
cout <<"Display Rational array:"<<endl;



file_op.close(); // close the streams
cout << "\n\nPress Enter to end ";
cin.ignore();


return 0;
}


User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/4/08 06:51PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month