Hi. I'm developing a stack using a linked list.
I have to develop two friend functions to do something with the list.
But I've tried to understand the friendship, without any consistent result.
Extract of code:
Code:
class Element {
public:
int Data;
Element *nextElement;
Element(int Element) {Data = Element; nextElement = NULL;}
~Element() { }
};
class Stack {
private:
Element *firstElement;
public:
Stack() { firstElement = NULL; }
~Stack() { }
bool isEmpty() { return firstElement == NULL; }
void push(int El)
{
Element *pElement = new Element(El);
pElement->nextElement = firstElement;
firstElement = pElement;
}
int pop()
{
if (isEmpty())
{
cout << "Empty stack";
exit(EXIT_FAILURE);
}
else
{
Element *pElement = firstElement;
firstElement = firstElement->nextElement;
int temp = pElement->Data;
delete pElement;
return temp;
}
}
void show()
{
Element *pElement = firstElement;
while(pElement != NULL)
{
cout << pElement->Data << "\n";
pElement = pElement->nextElement;
}
}
friend int ::count(Stack& stack);
friend void ::extract(Stack& stack);
};
When I try to define the friend function outside the class in order to do something (e.g. count the element of the stack) I get errors.
I try to define them this way:
Code:
int Stack::count(Stack& stack)
{
//Do something
}
I have: Method count does not have declaration.
If I declare like:
Code:
int count(Stack& stack)
{
//Do something
}
I have no errors, but I cannot access the private properties of the class.
The thing I would like to do is: sum the elements of the stack with a friend function.
Please help me understand how it works.
Thank you.