我在用c++实现一个链式栈的时候,我想用c++特别的重载方式,实现对栈的一个对象的输出,例如 stack<int> st ; cout<<st; 然而实现这一个小小的重载真的很艰辛
代码如下:
#pragma once #include #include #include using namespace std; template class stack; //template //class ListNode; //template //ostream& operator<<(ostream&ou,ListNode<Type> r); template class ListNode { friend class stack; public: ListNode() :data(Type()), link(NULL) {} ListNode(Type d, ListNode* next = NULL) :data(d), link(next) {} ~ListNode() {} friend ostream& operator<< (ostream& ou, ListNode& r); friend ostream& operator<< (ostream& out, stack& R); private: Type data; ListNode* link; }; //template //ostream& operator<<(ostream& out,stack<Type> R); template class stack { public: stack() { top = NULL; } ~stack() { Destroy(); } public: bool Empty() { return top == NULL; } void Push(Type x) { if (Empty()) { top = new ListNode(x); } else { top = new ListNode(x, top); } } /*void Show() { if (Empty()) { return; } else { ListNode* cur = top; while (cur != NULL) { cout << cur->data << " "; cur = cur->link; } } cout << endl; }*/ void Pop() { if (Empty()) { return; } else { ListNode* rm = top; top = top->link; delete rm; } } void Pop(Type& e) { if (Empty()) { return; } else { e = top->data; ListNode* rm = top; top = top->link; delete rm; } } Type Gettop() { if (Empty()) return NULL; else return top->data; } int Length() { int count = 0; if (Empty()) { } else { ListNode* cur = top; while (cur != NULL) { count++; cur = cur->link; } } return count; } void Destroy() { if (Empty()) { return; } else { ListNode* rm = top; while (top != NULL) { rm = top; top = top->link; delete rm; } } } friend ostream& operator<< (ostream& out, stack& R); private: ListNode* top; }; template ostream& operator<& r) { ou << r.data; return ou; } template ostream& operator<& R) { out << "top:"; ListNode* cur = R.top; while (cur != NULL) { out << *cur; out << " "; cur = cur->link; } out << "base"; out << endl; return out; } //测试代码 #include "stack.h" int main() { stack st; st.Push(23); st.Push(24); st.Push(25); st.Push(26); cout << st; st.Push(27); cout << st; int a=st.Gettop(); cout << a << endl; st.Pop(); cout << st; return 0; }
通过写这个stack我发现一些东西还是需要把握的。
1.在实现的时候可以只将stack封装起来,而把ListNode暴露出来,这样可以方便很多。否则数据的实现特别麻烦,首先stack必须为ListNode的友元类,其次还是为了访问ListNode的私有成员,我不得不把stack的友元函数在ListNode类里卖弄声明一下,大家如果看的仔细的话,应该有下面两条语句。
friend ostream& operator<< (ostream& ou, ListNode& r);
friend ostream& operator<< (ostream& out, stack& R);
为了访问ListNode的私有数据我们做了很复杂的处理,如果ListNode是公有的,那么访问起来方便多了,而且我们主要的实现方法都是在stack里面实现的,而我们把stack封装起来就行了。
2.
friend ostream& operator<< <Type>(ostream& ou, ListNode<Type>& r);
friend ostream& operator<< <Type>(ostream& out, stack<Type>& R);