类,指针函数,数组组合使用

//my_stack.h
//基于动态数组的栈实现
#ifndef __MY_STACK_H__
#define __MY_STACK_H__

class MyStack
{
public:
    MyStack(int size, int Mode);
    ~MyStack();
    void push(int value);
    int pop()
    {
        return pDynStack[--m_nSp];
    }
    int top()
    {
        return pDynStack[m_nSp - 1];
    }
    int isEmpty() const
    {
        return m_nSp <= 0;
    }    

    int operator=(int nIndex)
    {
        return pDynStack[nIndex];
    }
    
private:
    int *pDynStack;
    int m_nSize;
    int m_nSp;
    int m_nMode;

private:    
    MyStack(const MyStack&);
    MyStack& operator=(const MyStack&);

public:
    void GrowArray(int i);
    void GrowArray2(int i);
};

#endif


#include "MyStack.h"
#include <memory.h>
#include <assert.h>
#include <stdio.h>

enum ARRAY_SIZE_
{   
    INITIAL_SIZE = 1,
    GROW_FACTOR = 2,
    GROW_SIZE = 100
};

enum GROW_ARRAY_MODE_
{
    GROW_FACTOR_MODE = 1,
    GROW_SIZE_MODE = 2
};

typedef void (MyStack::*pfunGrowArrayFun)(int i);
static pfunGrowArrayFun g_GrowArrayStruct[] = 
{
    &MyStack::GrowArray,
    &MyStack::GrowArray2
};

MyStack::MyStack(int size, int Mode)
:m_nSize(size > INITIAL_SIZE ? size: INITIAL_SIZE)
,m_nSp(0)
{
    pDynStack = new int[m_nSize];
    assert(pDynStack);
    m_nMode = Mode;
}

MyStack::~MyStack()
{
    delete [] pDynStack;
    pDynStack = NULL;
}

void MyStack::push(int value)
{
    if (m_nSp >= m_nSize)
    {
        (this->*g_GrowArrayStruct[m_nMode])(m_nSp);
    }
    pDynStack[m_nSp++] = value;
}

void MyStack::GrowArray(int i)
{
#ifdef PRINT
    printf("GrowArray[%d].\n", i);
#endif
    int *p = pDynStack;
    m_nSize *= GROW_FACTOR;
    pDynStack = new int[m_nSize];
    assert(pDynStack);
    memcpy(pDynStack, p, m_nSp * sizeof(int));
    delete [] p;
    p = NULL;
}

void MyStack::GrowArray2(int i)
{
#ifdef PRINT
    printf("GrowArray2[%d].\n", i);    
#endif
    int *p = pDynStack;
    m_nSize += GROW_FACTOR;
    pDynStack = new int[m_nSize];
    assert(pDynStack);
    memcpy(pDynStack, p, m_nSp * sizeof(int));
    delete [] p;
    p = NULL;
}

int main()
{
    MyStack mytest(10, GROW_FACTOR_MODE);
    for (int i = 0; i < 50; i++)
    {
        mytest.push(i);
    }
    
    return 0;
}

CFLAGS+=-g -Wall
all:
	g++ ${CFLAGS} MyStack.h MyStack.cpp -o MyStack
clean:
	rm -rf MyStack

$/app/user/~: make CFLAGS+=-DPRINT

你可能感兴趣的:(类,指针函数,数组组合使用)