2013-12-17 2 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

'using namespace project'는 ** 네임 스페이스 내부 ** 함수 정의와 동일하지 않습니다 **. 이 정의를'네임 스페이스 프로젝트 {...} '안에 넣어야합니다. –

2

함수 구현도 project 네임 스페이스에 있어야합니다. 사용하는 것으로 충분하지 않다고 선언하면 기능 자체를 'global'로 지정하면 해당 함수 자체가 'global'이됩니다. 잘못된 네임 스페이스 범위에서 friended되기 때문에 멤버에 액세스하십시오.

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 
} 
관련 문제