0

I have a matrix class that can keep a 2d matrix, assign, print the matrix

class Matrix
{
    private:
    int Row;
    int Column;
    int **Member;
    int *storage;
    public:
    Matrix()
    {}
    Matrix(int row,int column)
    {
        Row = row;
        Column = column;
        Member = new int*[row];
        storage = new int[row*column];
        for (int i = 0; i < row; ++i)
        {
            Member[i] = storage + column * i;
        }

        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < column; j++)
            {
                Member[i][j] = 0;
            }
        }
    }

    ~Matrix()
    {
        free(storage);
        free(Member);
    }


    void print()
    {
        for (int i = 0; i < Row; i++)
        {
            for (int j = 0; j < Column; j++)
            {
                cout << Member[i][j] << " ";
            }
            cout << endl;
        }
    }


    void assign(int row ,int column,int value)
    {
        if (((row > Row) || (column > Column)) ||  ((row <= 0) || (column <= 0)))
        {
            cout << "Error : Index out of range." << endl;
        }
        else
        {
            Member[row-1][column-1] = value;
        }
    }
};

and I want to use operator overloading >> to read from txt file to class and << to write to a txt file

This is an example that in need to use in main

int main()
{
    Matrix m1;
    ifstream fin;
    fin.open("input.txt"); 
    
    fin >> m1;

    fin.close();

    ofstream fout;
    fout.open("output.txt"); 
    
    fout << m1;

    fout.close();
}

How can I use the istream and ostream to read and write to file I really don't get it I can do only input and output in cin and cout oop is very hard for me ;-;

  • 1
    "*I can do only input and output in cin and cout*" - `cin` is an `istream`, and `cout` is an `ostream`. So what exactly are you having trouble with trying to generalize your reading/writing code to work with any `istream`/`ostream`? There is no overloaded operators in the code you have shown, so what exactly have you tried that is not working for you? – Remy Lebeau Apr 12 '22 at 19:25
  • Future bug: Don't mix `new` and `free`. `delete` what you `new`, `delete[]` what you `new[]`, and `free` what you get from the `*alloc` family of C functions. But only do this as a last resort. Prefer to use a library container like `std::vector`. – user4581301 Apr 12 '22 at 19:34
  • Side note: [The Rule of Three](https://en.cppreference.com/w/cpp/language/rule_of_three) says that if you have a destructor, copy constructor or assignment operator you almost always need all three. You have a destructor managing a resource so you must also ensure the resource is copied and assigned correctly. – user4581301 Apr 12 '22 at 19:37

0 Answers0