【问题标题】:My ostream and istream friend function can't access private class members我的 ostream 和 istream 好友功能无法访问私人班级成员
【发布时间】:2015-09-25 15:16:45
【问题描述】:

我的代码:

ma​​trix.h

#include <iostream>

class Matrix {
private:
    int row;
    int col;
    int **array;

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

ma​​trix.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;
}

ma​​in.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. 二进制“
  5. 'ostream':不明确的符号
  6. 'istream':模棱两可的符号

我做错了什么? :(

**已编辑:我已编辑问题以提供像 Barry 建议的 MCVE 示例,并像 Slava 推荐的那样删除了 using namespace std。我仍然遇到同样的错误。

【问题讨论】:

  • 请提供minimal, complete, and verifiable exampleMatrix 是命名空间吗?
  • 我发布的是我的确切代码。我唯一遗漏的部分是使用“...”@Barry 的其他功能
  • 您的矩阵类不包括&lt;iostream&gt;?或者有一个结束};
  • 哦,确实有 };但不,它不包括 。这就是它不起作用的问题吗? @巴里
  • 请查看 MCVE 链接并发布完整示例。如果没有完整且可验证的示例,就不可能知道问题所在。

标签: c++ matrix friend-function


【解决方案1】:

既然你有一个完整的例子,你在这里缺少std::

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

添加它,一切编译正常:

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

【讨论】:

    【解决方案2】:

    我做错了什么? :(

    将声明using namespace std; 放入标题是一种不好的做法,这是有原因的。据此:

    'ostream':模棱两可的符号 'istream': 模棱两可的符号

    您在某个全局命名空间中声明了 istream 和 ostream。遵循良好的习惯,输入std::并不难

    【讨论】:

    • 好的,这是新编辑的代码。我已经听从了你的建议。不确定我是否做得对,虽然 cz 我是 C++ 新手,而且我一直在所有程序中使用 using namespace std。我仍然可以在 Main.cpp 中使用 using namespace std 对吗?
    • @ChewingSomething 显示确切的错误,而不是您的解释
    猜你喜欢
    • 2021-08-05
    • 2016-11-02
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多