-1

我有 2d 数组,它代表矩阵,我需要通过重载的 << 运算符打印它。

该重载运算符的声明是

std::ostream &operator <<(std::ostream &os, const Matrix &matrix) {

return os;
}

而且效果很好——当我写的时候

 ostringstream os;
 Matrix a;
 // fill in the matrix
 os << a;

这个函数被调用......但是虽然我已经阅读了一些教程,但我没有找到,如何让它打印出值......有人可以告诉我 soma 示例代码,如何实现一些非常从矩阵中打印出值的基本操作?

顺便说一句-矩阵可以有随机大小..

4

2 回答 2

1

You either need to write the result from the ostringstream to cout:

ostringstream os;
Matrix a;
// fill in the matrix
os << a;
cout << os.str();

or you do it directly:

Matrix a;
// fill in the matrix
cout << a;
于 2013-04-04T21:49:32.493 回答
0

Without seeing your Matrix class definition it's hard to guess how it's implemented, but you probably want something like this:

std::ostream& operator<< (std::ostream &os, const Matrix &matrix) {
    for (int i = 0; i < matrix.rows; ++i)
    {
        for (int j = 0; j < matrix.cols; ++j)
            os << " " << matrix.data[i * matrix.cols + j];
        os << std::endl;
    }
    return os;
}

To display the matrix you would then just do this:

 Matrix a;
 // fill in the matrix
 cout << a;

This invokes the above operator<< implementation to print the matrix to stdout. Obviously you can use any other appropriate output stream instead of cout.

于 2013-04-04T21:32:19.577 回答