Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef MATRIX_H
- #define MATRIX_H
- class matrix{
- public:
- matrix(size_t rows, size_t cols);
- matrix(const matrix& other);
- ~matrix();
- void addAt(size_t i, size_t j, int num){
- arr[i][j] = num;
- }
- matrix& operator*(const matrix& rhs);
- void print() const{
- for (size_t i = 0; i < rows; i++){
- for (size_t j = 0; j < cols; j++){
- std::cout << arr[i][j] << ", ";
- }
- std::cout << std::endl;
- }
- }
- int **arr;
- private:
- void delMatrix();
- void copyMatrix(const matrix& other);
- size_t rows;
- size_t cols;
- };
- matrix::matrix(size_t rows, size_t cols) : rows(rows), cols(cols){
- arr = new int*[rows];
- for (size_t i = 0; i < rows; i++){
- arr[i] = new int[cols];
- }
- for (size_t i = 0; i < rows; i++){
- for (size_t j = 0; j < cols; j++){
- arr[i][j] = 0;
- }
- }
- }
- matrix::matrix(const matrix& other){
- copyMatrix(other);
- }
- matrix::~matrix(){
- delMatrix();
- }
- matrix& matrix::operator=(const matrix& other){
- if (this != &other){
- delMatrix();
- copyMatrix(other);
- }
- return *this;
- }
- /*matrix& matrix::operator*=(const matrix& rhs){
- matrix temp = rhs;
- return temp;
- }*/
- matrix& matrix::operator*(const matrix& rhs){
- matrix temp(rows, rhs.cols);
- for (size_t i = 0; i < temp.rows; i++){
- for (size_t j = 0; j < temp.cols; j++){
- for (size_t k = 0; k < temp.rows; k++){
- temp.arr[i][j] += arr[i][k] * rhs.arr[k][j];
- }
- }
- }
- return temp;
- }
- void matrix::delMatrix(){
- for (size_t i = 0; i < rows; i++){
- delete[] arr[i];
- }
- delete arr;
- }
- void matrix::copyMatrix(const matrix& other){
- rows = other.rows;
- cols = other.cols;
- arr = new int*[rows];
- for (size_t i = 0; i < rows; i++){
- arr[i] = new int[cols];
- }
- for (size_t i = 0; i < rows; i++){
- for (size_t j = 0; j < cols; j++){
- arr[i][j] = other.arr[i][j];
- }
- }
- }
- #endif
- #include <iostream>
- #include "matrix.h"
- int main() {
- matrix *A, *B;
- A = new matrix(3, 3);
- B = new matrix(3, 2);
- A->addAt(0, 0, 1);
- A->addAt(0, 1, 2);
- A->addAt(0, 2, 3);
- A->addAt(1, 0, 4);
- A->addAt(1, 1, 5);
- A->addAt(1, 2, 6);
- A->addAt(2, 0, 7);
- A->addAt(2, 1, 8);
- A->addAt(2, 2, 9);
- A->print();
- std::cout << std::endl;
- B->addAt(0, 0, 1);
- B->addAt(0, 1, 2);
- B->addAt(1, 0, 3);
- B->addAt(1, 1, 4);
- B->addAt(2, 0, 5);
- B->addAt(2, 1, 6);
- B->print();
- std::cout << std::endl;
- std::cout << (*A**B).arr[0][1];
- std::cout << std::endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement