You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++复制赋值运算符失效及doubleCap函数内存问题求助

解决你的C++ NumList类两个问题

咱们逐个搞定你遇到的这两个问题:

问题1:复制赋值运算符无法正常工作

你的复制赋值运算符实现里漏掉了对size成员变量的赋值!在完成数组元素复制后,没有把源对象的size同步到当前对象,导致目标数组numArr2的size还是默认的0,调用print()时循环根本不会执行,自然看不到输出内容。

修改后的复制赋值运算符代码:

NumList& NumList::operator= (const NumList& anotherNumList) {
    // 检查是否是自赋值
    if (this == &anotherNumList)
        return *this;
    // 释放旧内存
    delete[] numList;
    this->capacity = anotherNumList.capacity;
    this->size = anotherNumList.size; // 新增:同步源对象的size值
    // 分配新内存并复制元素
    numList = new int[capacity];
    for (int i = 0; i < anotherNumList.size; ++i) {
        numList[i] = anotherNumList.numList[i];
    }
    return *this;
}

问题2:doubleCap函数中delete[] newArr导致随机值

这是典型的悬垂指针问题:你执行numList = newArr;后,numList和newArr指向了同一块堆内存。此时调用delete[] newArr;会直接释放这块内存,numList就变成了指向已释放内存的野指针,后续访问numList的元素时,读取到的就是随机的垃圾值。

正确的做法是:不要在这里删除newArr,因为我们已经把numList指向了这块新内存,后续会在析构函数里通过delete[] numList;来统一释放它。你原始代码中去掉delete[] newArr;的操作是对的,留着才会出问题。

另外顺便提个小细节:insertAt函数里的索引越界判断应该是index < 0 || index > size,而不是index > capacity——插入位置最多只能是当前元素的末尾(即等于size的位置),超过size的位置是无效的,比如当前size是2,插入到index=2是合法的(追加到末尾),但index=3就不行了。

修改后的insertAt越界判断:

if (index < 0 || index > size) {
    cout << "The index is out of range." << endl;
}

修改后预期输出

完成以上修改后,运行你的main函数,就能得到正常的输出:

List 1 after inserting 10: 10
List 1: 5 10 11 12

Print the list 2 of int: 10

Print the list 3 of int: 10
Press any key to continue . . .

内容的提问来源于stack exchange,提问作者Coded-Blood Junior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:17:50