I get a syntax error for this code, a c2143 error, the visual studio says the error is in the 7th line inside the class node definition. if someone can please tell me what the error is I just don't get it.
#include <iostream>
using namespace std;
template<class T>
class Node
{
friend LinkedStack<T>;
private:
T data;
Node<T> *link;
};
template<class T>
class LinkedStack {
public:
LinkedStack() {top = 0;}
~LinkedStack();
int IsEmpty() const {return top == 0;}
T Top() const;
LinkedStack<T>& Add(const T& x);
LinkedStack<T>& Delete(T& x);
private:
Node<T> *top;
};
template<class T>
LinkedStack<T>::~LinkedStack()
{// Stack destructor..
Node<T> *next;
while (top) {
next = top->link;
delete top;
top = next;
}
}
template<class T>
T LinkedStack<T>::Top() const
{// Return top element.
if (IsEmpty()) cout<<"Stack empty:";
else
return top->data;
}
template<class T>
LinkedStack<T>& LinkedStack<T>::Add(const T& x)
{// Add x to stack.
Node<T> *p = new Node<T>;
p->data = x;
p->link = top;
top = p;
return *this;
}
template<class T>
LinkedStack<T>& LinkedStack<T>::Delete(T& x)
{// Delete top element and put it in x.
if (IsEmpty())
{
cout<<"Stack empty";
return *this;
}
x = top->data;
Node<T> *p = top;
top = top->link;
delete p;
return *this;
}
void main(void)
{
int x;
LinkedStack<int> S;
S.Add(1).Add(2).Add(3).Add(4);
cout << "Stack should be 1234" << endl;
cout << "Stack top is " << S.Top() << endl;
S.Delete(x);
cout << "Deleted " << x << endl;
S.Delete(x);
cout << "Deleted " << x << endl;
S.Delete(x);
cout << "Deleted " << x << endl;
S.Delete(x);
cout << "Deleted " << x << endl;
}
You have:
friend LinkedStack<T>;
Shouldn't it be:
friend class LinkedStack<T>;
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.