C/C++函數挪用棧的完成辦法。本站提示廣大學習愛好者:(C/C++函數挪用棧的完成辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C/C++函數挪用棧的完成辦法正文
本文實例講述了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;
}
願望本文所述對年夜家的C++法式設計有所贊助。