改造栈类,使其使用于坐标类
-main文件
#include <iostream>
#include "Mystack.h"
#include "Coordinate.h"
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
Mystack *pStack = new Mystack(5);//初始化操作
//将Coordinate 作为对象传入
pStack->push( Coordinate( 1,1 )); //底
pStack->push( Coordinate( 2,2 ));
cout << "The length of Stack is "<<pStack->stackLength() << endl << endl;
pStack->stackTraverse();
cout << endl << "get one from stack: " << endl;
Coordinate elem;
pStack->pop(elem);
pStack->stackTraverse();
cout << "The length of Stack is "<<pStack->stackLength() << endl << endl;
if(pStack->stackEmpty())//判断是否为空
cout << "Empty" << endl;
Mystack mystack(4);
mystack.push(Coordinate(3,3));
mystack.stackTraverse();
cout << endl << endl;
cout << "The length of the Stack is " << mystack.stackLength();
delete pStack;
pStack = NULL;
return 0;
}
- Mystack头文件
Coordinate *m_p
;//栈空间指针,指向Coordinate
对象
#ifndef MYSTACK_H## 标题
#define MYSTACK_H
#include "Coordinate.h"
class Mystack
{
public:
Mystack(int size);
~Mystack();
bool stackEmpty();
bool stackFull();
void clearStack();
int stackLength();
bool push(Coordinate elem);
bool pop(Coordinate &elem);
void stackTraverse();
protected:
Coordinate *m_p;//栈空间指针
int m_iSize;//栈容量
int m_iTop;
};
#endif
- Mystack cpp文件
#include <iostream>
#include "Mystack.h"
#include "Coordinate.h"
using namespace std;
Mystack:: Mystack(int size){
m_iSize = size;
m_p = new Coordinate[size];//Coordinate如果不是默认构造函数,则会发生错误,只能申请一个对象
m_iTop = 0;
}
Mystack::~Mystack(){
delete []m_p;
}
bool Mystack::stackEmpty(){
if( 0 == m_iTop ){
return true;
}
else
return false;
}
bool Mystack::stackFull(){
if( m_iSize == m_iTop )
return true;
else
return false;
}
void Mystack::clearStack(){
m_iTop = 0;
}
int Mystack::stackLength(){
return m_iTop;
}
bool Mystack::push(Coordinate elem){
if( stackFull() ){
return false;
}
m_p[m_iTop] = elem;
m_iTop++;
return true;
}
bool Mystack::pop( Coordinate &elem){
if( stackEmpty() )
return false;
else
elem = m_p[--m_iTop];
return true;
}
void Mystack::stackTraverse(){
int temp = 0;
while( temp < m_iTop ){
//cout << m_p[temp] << " ";
m_p[temp].printCoordinate();
temp ++;
}
}
#endif
- Coordinated头文件
#ifndef COORDINATE_H
#define COORDINATE_H
class Coordinate
{
public:
Coordinate( int x = 0,int y = 0 );//默认构造函数
void printCoordinate();
protected:
int m_iX;
int m_iY;
};
#endif
- Coordinate cpp文件
#include "Coordinate.h"
#include <iostream>
using namespace std;
Coordinate::Coordinate(int x ,int y ){
m_iX = x;
m_iY = y;
}
void Coordinate::printCoordinate(){
cout << "x = " << m_iX << " " << "y = " << m_iY << endl;
}
- 运行结果
- C++类模版知识,运用类模版完成类模版栈