我的 ostream 和 istream 好友函数无法访问私有类成员
My ostream and istream friend function can't access private class members
我的代码:
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")不可访问
- binary '<<':找不到右操作数为'Matrix'的操作符
- 'ostream':歧义符号
- '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::
相关文章:
- C++ 传递指向对象的指针的指针,无法访问成员
- 从不同C++类的成员变量访问成员函数
- 使用 getter 访问成员变量C++
- 如何使用包含内部类的类实例有效地从内部类访问成员?
- 通过多个类访问成员时出错
- 如何在使用对象指针时访问成员函数
- 为什么相应成员不能正确访问成员函数指针
- 从两个不同类继承的非虚拟基类的访问成员
- 如何使用 gcc 内联汇编器代码访问成员变量
- 如何使用常数向量访问成员函数
- 访问成员函数中参数的类成员
- C++嵌套结构初始化和访问成员
- 通过指向班级第一个成员的指针访问成员是不确定的行为吗?
- 如何使用C STD :: SET中的迭代器访问成员功能
- 访问成员C 时,结构的向量生成了范围的错误
- 带指针的班级访问成员
- 从聚合类访问成员变量
- 如何访问成员变量 sqlite 回调
- ctypes/C++segfault访问成员变量
- 通过父类型的指针或直接从派生类访问成员函数的差异