Advertisement
bueddl

Untitled

Apr 28th, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <string>
  2.  
  3. class Matrix {
  4. public:
  5.     Matrix(size_t RowCount, size_t ColumnCount);
  6.     Matrix(Matrix && rhs);
  7.     ~Matrix();
  8.  
  9.     Matrix& operator=(Matrix && rhs);
  10.  
  11.     friend Matrix operator*(const Matrix &lhs, const Matrix &rhs);
  12.     // Matrix& operator*=(const Matrix &rhs);  // nicht möglich?
  13.  
  14. private:
  15.     void alloc_space();
  16.  
  17.     const size_t rowCount;
  18.     const size_t columnCount;
  19.  
  20.     double *elements;
  21. };
  22.  
  23. Matrix::Matrix(size_t RowCount, size_t ColumnCount)
  24.     : rowCount(RowCount), columnCount(ColumnCount)
  25. {
  26.     alloc_space();
  27. }
  28.  
  29. Matrix::~Matrix()
  30. {
  31.     delete[] elements;
  32. }
  33.  
  34. void Matrix::alloc_space()
  35. {
  36.     elements = new double[rowCount * columnCount];
  37. }
  38.  
  39. Matrix& Matrix::operator=(Matrix && rhs)
  40. {
  41.     delete[] elements;
  42.  
  43.     elements = rhs.elements;
  44.     rowCount = rhs.rowCount;
  45.     columnCount = rhs.columnCount;
  46.  
  47.     delete[] rhs.elements;
  48.     rhs.elements = nullptr;
  49.     rhs.rowCount = 0;
  50.     rhs.columnCount = 0;
  51.  
  52.     return *this;
  53. }
  54.  
  55. Matrix operator*(const Matrix &lhs, const Matrix &rhs)
  56. {
  57.     Matrix prod{lhs.rowCount, rhs.columnCount};
  58.  
  59.     if (lhs.columnCount != rhs.rowCount) {
  60.         // throw math error
  61.     }
  62.  
  63.     for (size_t m = 0; m < prod.rowCount; m++) {
  64.         for (size_t n = 0; n < prod.columnCount; n++) {
  65.             prod.elements[m * prod.columnCount + n] = 0;
  66.  
  67.             for (size_t k = 0; k < lhs.columnCount; k++) {
  68.                 prod.elements[m * prod.columnCount + n] +=
  69.                     lhs.elements[m * lhs.columnCount + k] * rhs.elements[k * rhs.rowCount + n];
  70.             }
  71.         }
  72.     }
  73.  
  74.     return std::move(prod);
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement