C ++使用new创建堆栈

问题描述

我必须使用new而不是realloc / malloc来创建具有动态分配的push函数。我已经建立了可以正常工作的程序,但是具有malloc和calloc函数,并且因为我开始学习c ++,所以我不知道如何更改它以使用new而不是malloc。当程序可用内存不足时,我还应该将堆栈的可用内存增加一倍。这是stack.cpp代码

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"

stack::stack()
{
    this->top = 0;
    this->data= (int *)malloc(0 * sizeof(int));
}

stack::~stack()
{
    free(this->data);
}

void stack::clear()
{
    this->top = 0;
}

void stack::push(int a)
{
    i = i * 2;
    assert(this->top < STACKSIZE);
    int *ptr = (int *)realloc(data,(this->top + 1) * sizeof(int));
    if (ptr == NULL)
    {
        return;
    }
    this->data = ptr;
    this->data[this->top++] = a;
}

int stack::pop()
{
    assert(this->top > 0);
    return this->data[--this->top];
}

并且有头文件

#define STACKSIZE 20

class stack
{
public:
    void push(int a);
    int pop();
    void clear();
    stack();
    ~stack();

private:
    int top;
    int *data;
};

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)