#include <stdexcept>
#include <iostream>
#ifndef MATRIX_H
#define MATRIX_H
class Matrix {
public:
Matrix() {
_a[0] = 0.0; _a[1] = 0.0;
_a[2] = 0.0; _a[3] = 0.0;
}
Matrix(double a00, double a01,
double a10, double a11)
{
_a[0] = a00; _a[1] = a01;
_a[2] = a10; _a[3] = a11;
}
Matrix(const Matrix& m) {
_a[0] = m._a[0]; _a[1] = m._a[1];
_a[2] = m._a[2]; _a[3] = m._a[3];
}
Matrix& operator= (const Matrix& m) {
_a[0] = m._a[0]; _a[1] = m._a[1];
_a[2] = m._a[2]; _a[3] = m._a[3];
}
// to return the elt (i,j) of a matrix
double operator() (int i, int j) const {
if (i < 0 || i > 1 || j < 0 || j > 1)
throw std::runtime_error("WrongIndex");
return _a[2*i + j];
}
// to access the elt (i,j) of a matrix and modify it
double& operator() (int i, int j) {
if (i < 0 || i > 1 || j < 0 || j > 1)
throw std::runtime_error("WrongIndex");
return _a[2*i + j];
}
private:
double _a[4]; // _a[0] = a00 _a[1] = a01
// _a[2] = a10 _a[3] = a11
};
// Write the code below corresponding to:
// 1) the addition of two matrices
// 2) the subtraction of one matrix from the other
// 3) the multiplication of two matrices
// In addition: overload the operator "<<" in order to nicely print a matrix
#endif // MATRIX_H
To test your code, you can type the following code in a file "test_matrix.cpp":
#include <iostream>
#include "Matrix.h"
int main() {
Matrix m1(1.0, 0.0, 1.0, 0.0);
Matrix m2;
m2(0,0) = 1.0;
m2(0,1) = 1.0;
m2(1,0) = 1.0;
m2(1,1) = 1.0;
Matrix m3;
m3 = m1 + m2;
std::cout << m3 << std::endl;
m3 = m1 - m2;
std::cout << m3 << std::endl;
m3 = m1 * m2;
std::cout << m3 << std::endl;
}
Create two files: "utils.h" and "test_generic_programming.cpp".
In "utils.h" write a template function min() that returns the minimum of two elements. You can get inspiration from the function max() defined in the lecture slides.
In "test_generic_programming.cpp" write a main() function to test your min() function. You can reuse a similar example to the one presented in the lecture slides.