初学者。。。自己学习的例子
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdlib.h>
using namespace std;
class CStuScore
{
public:
CStuScore()//默认构造函数
{
}
CStuScore(CStuScore &one)//默认拷贝构造函数
{
strcpy(strName, one.strName);
strcpy(strStuNo, one.strStuNo);
fScore[0] = one.fScore[0];
fScore[1] = one.fScore[1];
fScore[2] = one.fScore[2];
}
void SetData(char *strname, char *strno, float s1, float s2, float s3)
{
strcpy(strName, strname);
strcpy(strStuNo, strno);
fScore[0] = s1;
fScore[1] = s2;
fScore[3] = s3;
}
void OutPut(void)
{
cout<<"姓名:"<<strName<<endl;
cout<<"学号:"<<strStuNo<<endl;
cout<<"成绩:"<<fScore[0]<<","<<fScore[1]<<","<<fScore[2]<<endl;
}
void Input(void)
{
cout<<"姓名:"; cin>>strName;
cout<<"学号:"; cin>>strStuNo;
cout<<"成绩:"; cin>>fScore[0]>>fScore[1]>>fScore[2];
}
private:
char strName[12];
char strStuNo[9];
float fScore[3];
};
class Cstack
{
public:
Cstack(int n_size)
{
m_size=n_size;
buffer=new CStuScore[m_size];
if(buffer!=NULL)
sp=buffer;
cout<<"栈空间已成功建立!"<<endl;
}
~Cstack()
{
if(buffer)
{
delete buffer;
buffer=NULL;
cout<<"栈空间释放!"<<endl;
}
}
void push(CStuScore a)//入栈:先入栈*sp=a,在sp++,sp总是指向下一个
{
if(sp>buffer+m_size){
cout<<"栈空间不足!"<<endl;
}else
*sp++=a;
}
CStuScore pop(void)//出栈:先sp--在弹出*sp
{
sp--;
if(sp<buffer){
cout<<"已越过栈底!"<<endl;
}
return *sp;
}
private:
CStuScore *sp;
CStuScore *buffer;
int m_size;
};
int main(void)
{
Cstack one(5);
CStuScore stu;
stu.Input();
one.push(stu);
stu.SetData("DING","001",99,98,97);
one.push(stu);
stu.SetData("ZHANG","002",97,98,99);
one.push(stu);
cout<<"开始进行弹出操作!"<<endl;
stu=one.pop();
stu.OutPut();
stu=one.pop();
stu.OutPut();
stu=one.pop();
stu.OutPut();
return 0;
}
<pre name="code" class="cpp">#include <iostream>
using namespace std;
typedef int T;
class Stack{
T a[5];
int cur;
public:
Stack():cur(0){};
void push(const T&d);
T pop();
const T& top()const;//栈顶数据
bool empty(){return cur==0;};
bool full(){return cur==5;};
void clear(){cur=0;};
int size(){return cur;};//栈数据个数
};
void Stack::push(const T&d){
if(full()) return;
a[cur++]=d;
}
T Stack::pop()
{
if(empty()) return 1;
return a[--cur];
}
const T& Stack::top()const
{
return a[cur-1];
}
int main()
{
Stack a;
a.push(1);
a.push(2);
a.push(3);
while(!a.empty()){
cout<<a.pop()<<endl;
}
};