std :: istream&运算符>>(std :: istream&,ClassName&)

时间:2018-11-26 14:53:47

标签: c++ visual-studio-2017

我检查了互联网,但找不到合适的东西。

如何有这样的主线(原始主线):

 int main()
    {
        Image left;
        std::ifstream ifs("left.txt");
        ifs >> left;
        ifs.close();
        waitForKey("cout << left");
        std::cout << left;
    }

并尝试这样(我的解码):

//m_pixel is a member that holds a single char
//m_H = height
//m_W = width
std::istream& operator>>(std::istream& is, ClassName& image)
{
    image.m_pixel = new Pixel*[image.m_H];

    for (int i = 0; i < image.m_H; i++)
        image.m_pixel[i] = new Pixel[image.m_W];
}

例如,如果我不知道高度和宽度,我该如何将'is'插入图像?我怎么知道他们?我又如何在图像中插入“是”字符呢?简而言之,如何解码此代码?

1 个答案:

答案 0 :(得分:3)

很明显,当您转储图像时,需要先转储尺寸:

std::ostream& operator<<(std::ostream& os, ClassName& image)
{
    os << image.m_H << " " << image.m_W;
    // Dump the rest as before
    return os;
}

然后再次读取它们,然后读取其余数据:

std::istream& operator>>(std::istream& is, ClassName& image)
{
    is >> image.m_H >> image.m_W;
    image.m_pixel = new Pixel*[image.m_H];

    for (int i = 0; i < image.m_H; ++i)
    {
        image.m_pixel[i] = new Pixel[image.m_W];
        for (int j = 0; j < image.m_W; ++j)
        {
             is >> image.m_pixel[i][j];
        }
    }
    return is;
}

但是正如@NathanOliver所说,请使用std::vector<Pixel>