我的ostream和istream朋友功能无法访问私人班级成员 [英] My ostream and istream friend function can't access private class members
本文介绍了我的ostream和istream朋友功能无法访问私人班级成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码:
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;
}
错误:
- 成员"Matrix :: row"(在第3行matrix.h中声明)无法访问
- 成员"Matrix :: col"(在第3行matrix.h中声明)不可访问
- 成员"Matrix :: array"(在第3行matrix.h中声明)无法访问
- 二进制'<<' :未找到采用矩阵"类型的右侧操作数的运算符
- 'ostream':模棱两可的符号
- 'istream':模棱两可的符号
我做错了什么? :(
**我已经编辑了问题,以给出像Barry建议的MCVE示例,并且还删除了像Slava建议的using namespace std
.我仍然遇到相同的错误.
**Edited: I've editted the question to give a MCVE example like Barry suggested, and also removed using namespace std
like Slava recommended. I'm still getting the same error.
推荐答案
既然您已经有了一个完整的示例,则在这里缺少std::
:
Now that you have a complete example, you're missing std::
here:
friend std::ostream& operator<<(ostream& output, const Matrix& m);
^^^
添加它,一切都可以正常编译:
Add it and everything compiles fine:
friend std::ostream& operator<<(std::ostream& output, const Matrix& m);
这篇关于我的ostream和istream朋友功能无法访问私人班级成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文