尝试实现我自己的 << 和 >> 流操作符来操作我的 Grid 对象

Trying to implement my own << and >> streaming operators to operate on my Grid object

我的任务是重载我自己的“<<”和“>>”流操作符,以便从我的网格中读取值和向其中写入值。我不确定如何使用我的 SaveGrid 和 LoadGrid 来实现它。我已经阅读了多个关于重载运算符的教程,这就是我目前所了解的。

我已经实现了 class 的朋友,但我不确定如何在我的 grid.cpp 中实现它们。

friend ostream& operator<<(ostream& out, Grid& grid);
friend istream& operator>>(istream& in, Grid& grid);

寻找一些关于如何实现它的建议,以便我可以使用我的重载运算符和 cout << grid 和 cin >> grid 等现有方法读入和读出,我很抱歉我没有明确说明这很好,但任何建议都值得赞赏。

Grid.cpp

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

    void Grid::LoadGrid(const char filename[])
    {
        ifstream newStream;
        newStream.open(filename);

        for (int y = 0; y < 9; y++)
        {
            for (int x = 0; x < 9; x++)
            {
                newStream >> m_grid[y][x];
            }
        }


    }



    void Grid::SaveGrid(const char filename[]) 
    {
        ofstream newStreamOut(filename);

        for (int y = 0; y < 9; y++)
        {
            for (int x = 0; x < 9; x++)
            {
                newStreamOut << m_grid[y][x] << " ";

            }
            newStreamOut << endl;
        }


    } 


    ostream& operator<<(ostream& out, Grid& grid)
    {
        grid.SaveGrid(out);
        return out;
    }

    istream& operator>>(istream& in, Grid& grid)
    {
        grid.LoadGrid(in);
        return in;
    }

Grid.h

#pragma once
#include<ostream>
using namespace std;
class Grid
{
public:
    Grid() {};
    ~Grid(){};

    friend ostream& operator<<(ostream& out, Grid& grid);
    friend istream& operator>>(istream& in, Grid& grid);

    void LoadGrid(const char filename[]);
    void SaveGrid(const char filename[]); 


private:

    int m_grid[9][9];
};

main.cpp

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

int main(int args, char** argv)
{
    Grid grid;
    grid.LoadGrid("Grid1.txt");
    grid.SaveGrid("OutGrid.txt");
    system("pause");
}

将逻辑从您的 LoadGridSaveGrid 函数(所有对您打开的文件流进行操作的东西)移动到您的 >><< 函数中。还要为您不应更改的对象添加 const

    ostream& operator<<(ostream& out, const Grid& grid)  // grid should be const
    {
        for (int y = 0; y < 9; y++)
        {
            for (int x = 0; x < 9; x++)
            {
                out << grid.m_grid[y][x] << " ";

            }
            out << endl;
        }
        return out;
    }

然后你的 LoadGridSaveGrid 函数只是调用流操作符的助手,但要注意打开文件流。

    void Grid::SaveGrid(const char filename[]) const   // *this should be const
    {
        ofstream newStreamOut(filename);

        newStreamOut << *this;
    }

但现在您可以将 Grid 输出到您想要的任何其他 ostream

std::cout << my_grid << "\n";

之后,对istream侧做同样的事情。