CPP | std流打印错误

CPP | std stream printing error

本文关键字:打印 错误 std CPP      更新时间:2023-10-16

我目前正在编程一个int矩阵在cpp。

我想添加一个打印函数,以如下方式打印数字:

1 2 3
7 6 9    
19 23 9

(每两个整数用空格隔开,行尾无空格)。所以我写了下面的代码:

std::ostream& IntMatrix::operator << (std::ostream& out) const
{
    for(int i = 0; i < this->num_row; i++)
    {
            int j;
            for(j = 0; j < this->num_col - 1; j++)
            {
                    out << this->mat[i][j] << " ";
            }
            out << this->mat[i][j] << endl;
    }
    return out;
}

在文件IntMatrix.cpp中。但是,每次我尝试编译代码时,都会发生以下情况:

error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'

该怎么办?

不使用类成员函数,而是使用全局命名空间的重载:

 std::ostream& operator << (std::ostream& out, const IntMatrix& m) {
 }

并声明为IntMatrix中的friend