我的 ostream 和 istream 好友函数无法访问私有类成员

My ostream and istream friend function can't access private class members

本文关键字:访问 成员 ostream istream 好友 函数 我的      更新时间:2023-10-16

我的代码:

matrix.h

#include <iostream>
class Matrix {
private:
    int row;
    int col;
    int **array;
public:
    Matrix();
    friend std::ostream& operator<<(ostream& output, const Matrix& m);
};

matrix.cpp

#include "matrix.h"
#include <iostream>
Matrix::Matrix()
{
    row = 3;
    col = 4;
    array = new int*[row];
    for (int i = 0; i < row; ++i)
    {
        array[i] = new int[col];
    }
    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < col; ++j)
        {
            array[i][j] = 0;
        }
    }
}
std::ostream& operator<<(std::ostream& output, const Matrix& m)
{
    output << "nDisplay elements of Matrix: " << std::endl;
    for (int i = 0; i < m.row; ++i)
    {
        for (int j = 0; j < m.col; ++j)
        {
            output << m.array[i][j] << " ";
        }
        output << std::endl;
    }
    return output;
}

main.cpp

#include "matrix.h"
#include <iostream>
using namespace std;
int main()
{
    Matrix a;
    cout << "Matrix a: " << a << endl;
    system("pause");
    return 0;
}
错误:

  1. 成员"Matrix::row"(在第3行Matrix .h"声明)不可访问
  2. 成员"Matrix::col"(在第3行Matrix .h"声明)不可访问
  3. 成员"Matrix::array"(声明于第3行Matrix .h")不可访问
  4. binary '<<':找不到右操作数为'Matrix'的操作符
  5. 'ostream':歧义符号
  6. 'istream':歧义符号

我做错了什么?(

**编辑:我已经编辑了这个问题,像Barry建议的那样给出一个MCVE的例子,并像Slava建议的那样删除了using namespace std。我还是得到相同的错误

现在您有了一个完整的示例,这里缺少std:::

friend std::ostream& operator<<(ostream& output, const Matrix& m);
                              ^^^

添加它,一切都可以正常编译:

friend std::ostream& operator<<(std::ostream& output, const Matrix& m);

我做错了什么?(

将语句using namespace std;放入header中是一种不好的做法,这是有原因的。根据这个:

'ostream':歧义符号'istream':歧义符号

在全局命名空间中声明了istream和ostream。遵循良好的实践,键入std::

并不那么困难