c++ - C++ 中类成员的动态分配

标签 c++ class dynamic-memory-allocation

我正在尝试学习 C++ 中的 POO。我有一个关于类中内存分配的问题。我想创建一个堆栈类。我有这段代码是用 C++ 编写的:

这是堆栈类:

class Stack {
    private:
        int *stackArray;
        int topLevel;

    public:
        // Constructor without par
        Stack() {
            stackArray = new int[NMAX];
            topLevel = -1; // stiva este NULL la inceput
        }

        Stack(int array_size) {
            stackArray = new int[array_size];
            topLevel = - 1;
        }

        ~Stack() {
            delete[] stackArray;
        }

        void push(int x) {
            int n_maxim = sizeof(stackArray) / sizeof(int);

            if (topLevel >= n_maxim - 1) {
                cout << "The stack is full !\n";
                return;
            }
            topLevel++;
            stackArray[topLevel] = x;
        }
};

这是主要功能:

int main() {
    int n;
    cout << "Introduceti numarul de elemente =";
    cin >> n;
    Stack *s = new Stack();
    s->push(6);
    s->push(10);
    return 0;
}

所以我的问题是内存分配不起作用,它不会从键盘读取大小为 NMAX(100) 或大小为 n 的“v”数组。所以 push 函数只适用于 1 个元素,因为我不知道为什么,在任何分配内存之后的 sizeof(v) 是 4。

最佳答案

您不能对动态分配的数组使用 sizeof(),它将返回 int* 指针本身的大小,而不是数组的大小指着。因此,您的类(class)必须跟踪数组大小。

此外,您的类没有实现 Rule of 3/5/0 .您需要添加一个复制构造函数和复制赋值运算符,以便您可以正确地复制数组。

试试这个:

#include <algorithm>

class Stack {
    private:
        int *stackArray;
        int arraySize;
        int topLevel;

    public:
        Stack(int array_size = NMAX) {
            stackArray = new int[array_size];
            arraySize = array_size;
            topLevel = -1;
        }

        Stack(const Stack &src) {
            stackArray = new int[src.arraySize];
            arraySize = src.arraySize;
            for (int i = 0; i < arraySize; ++i)
                stackArray[i] = src.stackArray[i];
            topLevel = src.topLevel;
        }

        ~Stack() {
            delete[] stackArray;
        }

        Stack& operator=(const Stack &rhs) {
            if (&rhs != this) {
                Stack temp(rhs);
                std::swap(stackArray, temp.stackArray);
                std::swap(arraySize, temp.arraySize);
                std::swap(topLevel, temp.topLevel);
            }
            return *this;
        }

        void push(int x) {
            if (topLevel >= (arraySize-1)) {
                cout << "The stack is full !\n";
                return;
            }
            topLevel++;
            stackArray[topLevel] = x;
        }
};

关于c++ - C++ 中类成员的动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58384627/

相关文章:

class - 从外部类访问内部类的成员 - TypeScript

c# - 索引超出范围。必须是非负数且小于集合的大小

c++ - 初始化类的静态(非常量)变量。

c++ - 我有 Visual Studio 错误调试断言失败

c++ - 为什么在某些机器上堆栈溢出,但在另一台机器上出现段错误?

c++ - 错误 : cannot convert 'Vector (*)(double, Vector)' to 'ForwardEulerSolver*' in initialization

c++ - C++编译过程

c++ - C++ 中的无限 While 循环

c++ - 使用析构函数是只删除动态分配的数组还是所有数组?

c - 结构自引用