手机
当前位置:查字典教程网 >编程开发 >C语言 >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++程序设计有所帮助。

【C/C++函数调用栈的实现方法】相关文章:

C与C++ 无参函数的区别解析

使用C语言实现CRC校验的方法

基于Protobuf C++ serialize到char*的实现方法分析

C++读写.mat文件的方法

C++ 模版双向链表的实现详解

基于C++内存分配、函数调用与返回值的深入分析

用C# 控制Windows系统音量的实现方法

getdate()函数的用法实例

如何通过函数指针调用函数(实现代码)

C语言解线性方程的四种方法

精品推荐
分类导航