2012-11-22 49 views
2

我試圖使用朋友函數超載< <運算符,但它由於某種原因沒有看到私有成員變量。任何想法爲什麼會發生這將是相當有益的。朋友函數不能看到私有成員變量

這裏的頭文件

class Set 
    { 
private: 
    struct Node 
    { 
     int val; 
     Node* link; 
    }; 

    Node *cons(int x, Node *p); 
    Node *list; 


public: 
    Set() {list = NULL;} 
    bool isEmpty() const; 
    int size() const; 
    bool member (int x) const; 
    bool insert (int x); 
    bool remove (int x); 
    void print() const; 
    const Set operator+(const Set &otherSet)const; 
    const Set operator*(const Set &otherSet)const; 
    Node* getSet()const{return list;} 
    void setList(Node *list); 
    friend ostream& operator <<(ostream& outputStream, const Set &set); 
    }; 

這裏的函數定義。

ostream& operator <<(ostream& outputStream, const Set &set) 
    { 
       Node *p; 
       p = list; 
       outputStream << '{'; 
       while(p->link != NULL) 
       { 
       outputStream << p->val; 
       p = p->link; 
       } 
       outputStream << '}'; 
       return outputStream; 
    } 
+0

'friend ostream&Set :: operator <<'? –

回答

5

的問題是不是與Node無障礙而是與它的適用範圍:非限定類型名稱不通過友誼的範圍成爲 - 你應該使用Set::Node代替。

同樣適用於list變量:它應該是set.list

隨着這兩個變化,your code compiles fine on ideone

+0

我實際上在我發佈之前嘗試過,並且仍然存在問題。 –

+1

哪一個私有變量拋出錯誤?節點定義或列表?正如dasblinkenlight發佈的,將'Node * p;'更改爲'Set :: Node * p;'和'p = list;'更改爲'set.list'也適用於我。 – haroldcampbell

+0

如果我記得正確,那麼Node和列表都有問題(沒有代碼在我面前)。上述建議基本上是修復。多謝你們! –

0

一個simplistic representation of your code是:

class A 
{ 
    struct MY 
    { 
     int a; 
    }; 
    friend void doSomething(A); 
}; 

void doSomething(A) 
{ 
    MY *b; 

} 
int main() 
{ 
    return 0; 
} 

問題在於:

MY *b; 

你的功能,因爲它是類A內部聲明無法理解的MY類型。 因此錯誤:

In function 'void doSomething(A)': 
Line 12: error: 'MY' was not declared in this scope 
compilation terminated due to -Wfatal-errors. 

爲了告訴函數找到MyA你需要使用結構全名

A::MY *b; 

一旦你這樣做的函數知道在哪裏尋找MY,因此可以找到它。
Working online sample