The example of this paper describes the implementation method of C + + function call stack. Can be used to implement a simple script interpreter. Share to everyone for your reference. The implementation methods are as follows:
Header File Declaration section:
Copy Code code as follows:
#pragma once
const int buffersize = 1024;
const int growfactor = 2;
This stack was 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* POPs (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;}
};
Implementation section:
Copy Code code as follows:
#include "stdafx.h"
#include "TStack.h"
#include "New.h"
void Tstack::p ush (void* D, size_t bytecount)
{
If memory is not enough
If run under Multithread envionment,
A lock or critical section should is 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::p op (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;
}
I hope this article will help you with the C + + program design.