首页 > 解决方案 > C++。类中指针数组的赋值运算符

问题描述

我的任务是stack使用指针数组创建类。但是,当我将一个类型的变量分配stack给它自己时,堆栈(或数组)的元素就变成了垃圾。所以这里是代码(字段是和array):stack_sizestack_capacity

stack& operator= (const stack& old)
{
    if (stack_size != old.stack_size) {//array and old.array could be the same
        delete[] array;
    }
    stack_size = old.stack_size;
    stack_capacity = old.stack_capacity;
    array = new int[stack_capacity];
    for (size_t i = 0; i < stack_size; ++i) {
        array[i] = old.array[i];
    }

    return *this;
}

但是,当我跑步时

std::cout << "Peek: " << c.peek() << "  Size: " << c.size() << std::endl;
std::cout << c << "\n\n";

输出(分配前)是:

Peek: 300  Size: 6
{ -88, 99, -100, 0, 200, 300 }

分配后 (stk = stk) 是:

Peek: -842150451  Size: 6
{ -842150451, -842150451, -842150451, -842150451, -842150451, -842150451 }

可能是什么问题呢?有什么我想念的吗?谢谢

标签: c++classpointersstack

解决方案


因为*thisold是同一个对象,所以和this->array是一样的old.array
这意味着您正在将未初始化的数据复制到

array = new int[stack_capacity];

进入自身。

传统的快速解决方法是首先检查自我分配,

if (this == &old)
    return *this;

更现代的解决方案是“复制和交换”成语,您可以在线阅读。


推荐阅读