2015-09-25 79 views
-1

我的代码:我的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; 
} 

为主。 cpp

#include "matrix.h" 
#include <iostream> 
using namespace std; 

int main() 
{ 
    Matrix a; 
    cout << "Matrix a: " << a << endl; 

    system("pause"); 
    return 0; 
} 

错误:

  1. 构件 “矩阵行::”(在第3行matrix.h声明“)是不可访问
  2. 构件 ”矩阵::栏“(在第3行matrix.h声明“)是不可访问
  3. 构件‘矩阵阵列::’(在第3行matrix.h声明”)是不可访问
  4. 二进制“< <”:没有操作员发现它采用类型“矩阵”的右边的操作数
  5. '的ostream':不明确的符号
  6. '的IStream':不明确的符号

我在做什么错? :(

**编辑:。我editted问题给予MCVE例如像巴里建议,并且也去掉using namespace std像斯拉瓦建议我仍然得到同样的错误

+0

请提供[最小,**完整* *和可验证的示例](http://www.stackoverflow.com/help/mcve)。 Matrix是一个命名空间吗? – Barry

+0

我发布的是我的确切代码。我唯一遗漏的部分是使用“...”的其他函数@Barry – ChewingSomething

+0

您的矩阵类不包含''?或者关闭'};'? – Barry

回答

2

现在,你有一个完整的例子,你在这里失踪std::

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

添加它,样样精编译:

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

啊啊,非常感谢你! :d – ChewingSomething

1

What am I doing wrong? :(

它是一个不好的做法,把声明using namespace std;成标题,有一个原因。根据这样的:。

'ostream': ambiguous symbol 'istream': ambiguous symbol

在全局命名空间中的某个地方你istream和ostream的声明遵循良好的做法,也不是那么难键入std::

+0

好的,这里是新的编辑过的代码..我遵循了你的建议。不知道我是否正确地做它虽然cz我是新来的c + +,我一直使用命名空间标准所有我的程序..我仍然可以使用命名空间标准在我的Main.cpp权利? – ChewingSomething

+1

@ChewingSomething显示确切的错误,而不是你的解释 – Slava