一个c/c++函数调用栈的实现

函数调用栈的实现。可用于实现简单的脚本解释器。

声明:

#pragma once

const int BUFFERSIZE = 1024;

const int growfactor = 2;

 

// this stack is used as call stack.

class TStack{

private:

size_t size;   // the stack length

size_t pos;   // the stack top position   

char *buffer;  // the buffer

private:

void push(void* D, size_t bytecount);  // the implementation of push

void* pop(size_t bytecount);  // the implementation of pop

public:

TStack(size_t _size = BUFFERSIZE, size_t _pos = 0);  // initialize

TStack(const TStack& o);  // copy

TStack& operator=(const TStack& o);  // assignment

void pushInt(int i) { push(&i, sizeof(int)); }  // push an int

void pushLong(long l) { push(&l, sizeof(long)); }  // push a long

void pushfloat(double f) { push(&f, sizeof(f));}  // push  a double

void pushPointer(void* p){ push(p, sizeof(p)); }

// int 

int popInt() { return *(int *)pop(sizeof(int));}  // pop an int

long popLong() { return *(long *)pop(sizeof(long)); }  // pop an int    

double* popfloat() { return (double*)pop(sizeof(double)); }  // pop a double

void* popPointer() { return pop(sizeof(void*)) ; }

void clear() { pos = 0; }  

};

 

实现:

 

#include "stdafx.h"

#include "TStack.h"

#include "new.h"

 

void TStack::push( void* D, size_t bytecount )

{

// if memory is not enough

// if run under multithread envionment,

// a lock or critical section should be added

if (pos + bytecount > size)

{   

  size_t oldsize = size;

       size *= growfactor;   

  char *newbuffer = new char[size];

  memcpy(newbuffer, buffer, oldsize);

  delete buffer;

  buffer = newbuffer;   

}

memcpy(buffer+pos, D, bytecount);

pos += bytecount;

}

 

void* TStack::pop( size_t bytecount )

{

// need synchronization for multithread environment

pos -= bytecount;

return &buffer[pos];

}

 

TStack::TStack( size_t _size , size_t _pos )

:size(_size),

pos(_pos),

buffer(new char[size])

{

}

 

TStack::TStack( const TStack &O )

:size(O.size),

pos(O.pos)

{

   buffer = new char[size];

   if (buffer != NULL)

   {

  memcpy(buffer, O.buffer, size);

   }

}

 

TStack& TStack::operator=( const TStack& O )

{

if (this == &O)

 return *this;     

    this->size = O.size;

this->pos = O.pos;

 

if (buffer != NULL)

{

delete buffer;

}

    buffer = new char[this->size]; 

if (buffer != NULL)

{

      memcpy(buffer, O.buffer, this->size);

}

return *this;

}

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值