2×2 Matrix in C++

This is a fairly simple 2×2 matrix calculator written in C++ with the values hard-coded.

Running

Download

You can copy the source code from below, or you can download it from here for $1. Be sure to click on “2×2 Matrix (source code)” in the dropdown list.

Source Code

main.cpp

#include <iostream>
#include "matrix.h"
#include "vector.h"
using namespace std;
int main(int argc, char** argv)
{
  Matrix m(20, 37, 42, 7);
  Vector v(12, 14);
  cout << "Matrix m(20, 37, 42, 7)\n\n" << m << endl;
  cout << "Vector v(12, 14)\n\n" << v << endl;
  cout << "(m * v):\n\n";
  cout << (m * v);
  return 0;
}

matrix.h

#ifndef MATRIX2_H
#define MATRIX2_H
#include <iostream>
#include "vector.h"
using namespace std;
class Matrix
{
  public:
    Matrix(float x1, float x2, float y1, float y2);
    Matrix operator*(Vector v);
    ~Matrix();
    friend ostream& operator<<(ostream& out, const Matrix& m);
  private:
    float** elements;
};
#endif

matrix.cpp

#include "matrix.h"
#include <iostream>
using namespace std;
Matrix::Matrix(float x1, float x2, float y1, float y2)
{
  elements = new float*[2];
  elements[0] = new float[2];
  elements[1] = new float[2];
  elements[0][0] = x1;
  elements[0][1] = x2;
  elements[1][0] = y1;
  elements[1][1] = y2;
}

Matrix Matrix::operator*(Vector v)
{
  float x1 = elements[0][0] * v.elements[0];
  float x2 = elements[0][1] * v.elements[0];
  float x3 = elements[1][0] * v.elements[1];
  float x4 = elements[1][1] * v.elements[1];
  Matrix m(x1, x2, x3, x4);
  return m;
}

Matrix::~Matrix()
{
  delete[] elements;
}
//
//ostream& operator<<(ostream& out, const Fraction& value)
//{
//  out << value.numerator() << "/" << value.denominator();
//    return out;
//}

ostream& operator<<(ostream& out, const Matrix& m)
{
  out << "elements[0][0] = " << m.elements[0][0] << endl;
  out << "elements[0][1] = " << m.elements[0][1] << endl;
  out << "elements[1][0] = " << m.elements[1][0] << endl;
  out << "elements[1][1] = " << m.elements[1][1] << endl;
  return out;
}

vector.h

#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
using namespace std;
class Vector
{
  public:
    Vector(float x1, float x2);
    ~Vector();
    friend ostream& operator<<(ostream& out, const Vector& v);
    friend class Matrix;
  private:
    float* elements;
};
#endif

vector.cpp

#include "vector.h"
#include <iostream>
using namespace std;

Vector::Vector(float x1, float x2)
{
  elements = new float[2];
  elements[0] = x1;
  elements[1] = x2;
}

Vector::~Vector()
{
  delete[] elements;
}

ostream& operator<<(ostream& out, const Vector& v)
{
  out << "elements[0] = " << v.elements[0] << endl;
  out << "elements[1] = " << v.elements[1] << endl;
  return out;
}