2012-11-22 50 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