【问题标题】:C++. Assignment operator of a pointer array in classC++。类中指针数组的赋值运算符
【发布时间】:2021-05-13 06:39:35
【问题描述】:

我的任务是使用指针数组创建类stack。但是,当我将stack 类型的变量分配给它自己时,堆栈(或数组)的元素就会变成垃圾。下面是代码(字段为arraystack_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++ class pointers stack


【解决方案1】:

由于*thisold 是同一个对象,所以this-&gt;arrayold.array 相同。
这意味着您正在将未初始化的数据复制到

array = new int[stack_capacity];

进入自己。

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

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

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

【讨论】:

    猜你喜欢
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多