2013-12-17 51 views
2

我收到了一個我無法解釋的錯誤。這裏是我的頭文件:與朋友功能無法訪問的會員

#include <iostream> 
using namespace std; 
namespace project 
{ 
#ifndef MATRIX_H 
#define MATRIX_H 

typedef int* IntArrayPtr; 
class Matrix 
{ 
public: 
    friend ostream& operator<<(ostream& out, const Matrix& object); 
    friend istream& operator>>(istream& in, Matrix& theArray); 
    //Default Constructor 
    Matrix(); 

    Matrix(int max_number_rows, int max_number_cols, int intial_value); 

    //Destructor 
    ~Matrix(); 
    //Copy Constructor 
    Matrix(const Matrix& right_side); 
    //Assignment Operator 
    Matrix& operator=(const Matrix& right_side); 

    void Clear(); 
    int Rows(); 
    int Columns(); 
    bool GetCell(int x,int y, int& val); 
    bool SetCell(int x,int y, int val); 
    //void Debug(ostream& out); 
private: 
    int initialVal; 
    int rows; 
    int cols; 
    IntArrayPtr *m; 
}; 
#endif 
} 

在這裏,我的定義:

ostream& operator<<(ostream& out, const Matrix& object) 
{ 
    for(int r = 0; r < object.rows; r++) 
    { 
    for(int c = 0; c < object.cols; c++) 
    { 
     out << object.m[r][c] << " "; 
    } 
out << endl; 
} 
return out; 
} 

它給我Matrix.h成員是不可訪問的錯誤,但我明確表示,他們是友元函數。

+6

我敢打賭,你這是因爲你沒有把實施相同的命名空間中的標題的類。 – dasblinkenlight

+0

這個定義在班裏嗎? – smac89

+0

dasblinkenlight是對的。感謝所有的快速反應! – user3112739

回答

0

這些函數定義位於哪裏?聲明friend將名稱注入namespace project。如果函數未在該名稱空間中定義,則它們是不同的函數而不是朋友。

+0

它在我的實現文件matrix.cpp中定義。我通過陳述「using namespace project;」包含在實現文件中。 – user3112739

+0

'使用名稱空間項目'是**不是**定義名稱空間內的函數**。你必須在'namespace project {...}'中包裝這些定義。 –

2

你的函數實現也應該駐留在project命名空間 - 只是聲明你使用它是不夠的,如果你沒有指定它,那麼函數本身就是'全局',然後將不能訪問成員,因爲它是在錯誤的命名空間範圍內加入的。

Compiles fine with this fix

Does not compile otherwise

0

嘗試在Matrix類以外定義您的兩個朋友函數。

像:

#include <iostream> 
using namespace std; 
namespace project 
{ 
#ifndef MATRIX_H 
#define MATRIX_H 

typedef int* IntArrayPtr; 
class Matrix 
{ 
public: 
    //Default Constructor 
    Matrix(); 

    Matrix(int max_number_rows, int max_number_cols, int intial_value); 

    //Destructor 
    ~Matrix(); 
    //Copy Constructor 
    Matrix(const Matrix& right_side); 
    //Assignment Operator 
    Matrix& operator=(const Matrix& right_side); 

    void Clear(); 
    int Rows(); 
    int Columns(); 
    bool GetCell(int x,int y, int& val); 
    bool SetCell(int x,int y, int val); 
    //void Debug(ostream& out); 
private: 
    int initialVal; 
    int rows; 
    int cols; 
    IntArrayPtr *m; 
}; 
ostream& operator<<(ostream& out, const Matrix& object); 
istream& operator>>(istream& in, Matrix& theArray); 

#endif 
}