Reputation: 1648
I'm trying to overload the << operator using a friend function, but it's not seeing the private member variables for some reason. Any ideas why this is happening would be quite helpful.
Here's the header file
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);
};
Here's the function definition.
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;
}
Upvotes: 2
Views: 2923
Reputation: 206656
A simplistic representation of your code is:
class A
{
struct MY
{
int a;
};
friend void doSomething(A);
};
void doSomething(A)
{
MY *b;
}
int main()
{
return 0;
}
The problem lies in:
MY *b;
Your function cannot understand the type of MY
since it is declared inside the class A
.
Hence the error:
In function 'void doSomething(A)':
Line 12: error: 'MY' was not declared in this scope
compilation terminated due to -Wfatal-errors.
In order to tell the function to find My
inside A
you need to use fully qualified name of the structure:
A::MY *b;
Once you do that the function knows exactly where to look for MY
and hence can find it.
Working online sample.
Upvotes: 1
Reputation: 727137
The problem is not with the accessibility of Node
but rather with its scope: the unqualified type name does not become in scope through friendship - you should use Set::Node
instead.
Same goes for the list
variable: it should be set.list
.
With these two changes in place, your code compiles fine on ideone.
Upvotes: 5