2015-09-25 78 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