下面是MyStack.h的代码:
#pragma once #ifndef MY_STACK #define MY_STACK class MyStack { struct Link{ void * data; Link * next; void initialize(void * dat,Link * nxt); }* head; //这里直接定义了一个变量 public: MyStack(); void push(void * dat); void * peek(); void * pop(); ~MyStack(); }; #endif
下面是MyStack.cpp的内容:
#include "stdafx.h" #include "MyStack.h" #include <cassert> using namespace std; void MyStack::Link::initialize(void *dat,Link *nxt){ data = dat; next = nxt; } MyStack::MyStack(){ head=0; } void MyStack::push(void * dat){ Link * newLink = new Link(); newLink->initialize(dat,head); head = newLink; } void *MyStack::peek(){ assert(head); return head->data; //时刻记得,栈为空的时候访问和删除元素都不行 } void *MyStack::pop(){ assert(head); Link * cur=head; head=head->next; void *dat=cur->data; delete cur; return dat; } MyStack::~MyStack() { Link * cur; while(head){ //????? cur=head; head=head->next; delete cur; } }
下面是main函数的代码:
#include "stdafx.h" #include <iostream> #include "MyStack.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { MyStack st; int a=30; st.push("hello"); st.push(&a); cout<<*(int *)st.pop()<<endl; //30 cout<<(char *)st.peek()<<endl; //hello 字符数组 cout<<*(char *)st.pop()<<endl; //h 字符数组的首个字符 return 0; }