Operator Overloading

  • + 0 comments

    This was a weird one:

    #include <iostream>
    #include <vector>
    #include <cstddef>
    
    class Matrix
    {
    public:
        Matrix() = default;
        Matrix(std::size_t rows, std::size_t columns)
            : m_rows {rows}
            , m_columns {columns}
            , m_matrix {std::vector<std::vector<int>>(m_rows, std::vector<int>(m_columns))}
        {
        }
            
        friend Matrix operator+(const Matrix& m1, const Matrix& m2)
        {
            // The matrix has to have depth
            Matrix m3 {m1.m_rows, m1.m_columns};
            
            for(std::size_t r {0}; r < m1.m_rows; ++r)
            {
                for(std::size_t c {0}; c < m1.m_columns; ++c)
                {
                    m3(r, c) = m1(r, c) + m2(r, c); 
                }
            }
            
            return m3;
        }
        
        friend std::ostream& operator<<(std::ostream& out, const Matrix& m)
        {
            for(const auto& r : m.m_matrix)
            {
                for(const auto& c : r)
                {
                    out << c << ' ';
                }
                
                out << '\n';
            }
            
            return out;
        }
        
        friend std::istream& operator>>(std::istream& in, Matrix& m)
        {
            // Loops through the matrix and populates it
            for(auto& r : m.m_matrix)
            {
                for(auto& c : r)
                {
                    in >> c;
                }
            }
            
            return in;
        }
        
        // Returns a reference to an element
        int& operator()(const std::size_t r, const std::size_t c)
        {
            return m_matrix[r][c];
        }
        
        // 'const' version of 'operator()'
        const int& operator()(const std::size_t r, const std::size_t c) const
        {
            return m_matrix[r][c];
        }
        
    private:
        std::size_t m_rows {};
        std::size_t m_columns {};
        std::vector<std::vector<int>> m_matrix {};
      
    };
    
    int main() 
    {
        int numCases {};
        std::cin >> numCases;
        
        while(numCases--)
        {
            std::size_t rows {};
            std::size_t columns {};
            
            std::cin >> rows >> columns;
            
            // Constructs blank matrices, could also use std::vector::clear()
            Matrix m1 {};
            Matrix m2 {};
            
            m1 = {rows, columns};
            m2 = {rows, columns};
            
            std::cin >> m1 >> m2; 
            
            std::cout << m1 + m2; 
        }
        
        return 0;
    }