C++ Programming
Homework 7
● Define a template class Matrix that behaves like a two dimmensional array. I'll outline it here for you,
but you'll have to do all the C++ specific implementation. Define each template class in a .h file with
the same name as the class. Do not define a .cpp file for either of the template classes. Define the
methods inside the class declaration (not separately down in the .cpp file as we have been doing for
non-template classes). REMEMBER: DO NOT COPY AND PASTE ANY CODE BECAUSE YOU
ARE STILL LEARNING THE LANGUAGE.
● Use this Makefile and use the make command to build your program each time. Note g++ will do
extra error checking with these new -W flags. You can select/copy/paste the red text below into a file
Makefile if you run vim on Makefile, go into insert mode, then paste (alt click on Linux). Make sure
there is a single tab character in front of the update commands below (the ones that are indented).
CXXFLAGS=-std=c++11 -Wpedantic -Wall -Wextra -Werror -Weffc++ -Wzero-as-null-pointer-constant
test_matrix: test_matrix.cpp
g++ $(CXXFLAGS) test_matrix.cpp -o test_matrix
clean:
/bin/rm test_matrix
● (30 points) Convert the following class Array into a template where the element type is a template
parameter. Define it in a file Array.h with the method definitions inside the class declaration. Be sure
you know what all the iomanip objects do in the print function (and know how to use them). A final
quiz question depends on your knowing and understanding them.
#include
class Array
{
private:
int len;
int * buf;
public:
Array( int newLen )
: len( newLen ), buf( new int[newLen] )
{
}
Array( const Array l )
: len( l.len ), buf( new int[l.len] )
{
for ( int i = 0; i
}
friend ostream operator print( out );
return out;
}
// note the overloading of operator ( cols );
}
int numRows()
{
return rows;
}
int numCols()
{
return cols;
}
Array operator [] ( int row )
{
return * m[row];
}
void print( ostream out )
{
// write this one too, but use Array::operator
void fillMatrix( Matrix m )
{
int i, j;
for ( i = 0; i m(10,5);
fillMatrix( m );
cout M(8,10);
fillMatrix( M );
cout m )
{
// insert a for loop that cause the exception
}
void test_double_matrix_exceptions()
{
// PUT YOUR TRY/CATCH AROUND THE INSTRUCTIONS BELOW
cout M(8,10);
fillMatrix( M );
cout << M;
generate_exception( M );
cout << “Done\n”;
}
int main()
{
for (int i=0; i<3; ++i)// although two loops is enough
{
test_int_matrix();
test_double_matrix();
test_double_matrix_exceptions();
}
return 0;
}