c++ - 为什么这种方法会给出两个不同的结果?

标签 c++ qt

所以我有一个名为 HugeInt 的类,它存储一个动态整数数组,每个位对应一个小数位 (arr[0] = 2^0, arr[1] = 2^1 ...)。所以我还有这个方法 reverse,它可以反转数字。但主要是它给出了两个不同的结果,有人能帮忙吗? DynArray 是我创建的动态数组类。它只包含一个 int 数组,它会根据我们是否要添加到数组来调整大小。 (不能使用 vector )

HugeInt HugeInt::reverse(){
    HugeInt hi;
    for (int i = 0; i < this->size; i++){
        hi.dyn.add(this->dyn[this->size - 1 - i]);
    }
    return hi;
}

我的打印功能:

void HugeInt::print(){
    dyn.print();
}

void DynArray::print(){
    for (int i = 0; i < nextIndex; i++){
        std::cout << arr[i];
    }
}

我的运营商=:

HugeInt& HugeInt::operator=(const HugeInt &b1)
{
    this->dyn = b1.dyn;
    this->size = b1.size;
    return *this;
}

当我运行这个时:

int main(int argc, char *argv[])
{
    HugeInt hi4("123456");

    hi4.print();
    cout << endl;
    cout << endl;
    hi4.reverse().print();
    cout << endl;
    cout << endl;
    hugeInt = hi4.reverse();
    hugeInt.print();
}

我得到这些结果:

123456

654321

3854321

Why is the last result different from the second result? I am not used to coding in c++ so I feel like it might be some kind of c++ thing I am overlooking?

UPDATE: ok so I am totally lost now. I changed my reverse() to :

HugeInt HugeInt::reverse()
{
    return *this;
}

我的主要是:

int main(int argc, char *argv[])
{
    HugeInt hi4("123456");

    hi4.reverse().print();
    cout << endl;
    cout << endl;
    hugeInt = hi4.reverse();
    hugeInt.print();
}

并得到结果

123456

3223456

ASCII 表上的 32 是“空格”,而 38 是 &,这是它之前所说的。我迷路了!

最佳答案

HugeInt HugeInt::reverse() 中的这一行不好

this->~HugeInt();

这意味着您第一次调用 hi4.reverse() 时,您会销毁 hi4

以后每次使用都是未定义的行为。

删除该行。我不知道您希望在那里做什么,但“什么都不做”可能是更好的选择。

关于c++ - 为什么这种方法会给出两个不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15735639/

相关文章:

c++ - 为什么我在使用 dynamic_cast 和模板时收到错误 "A is an inaccessible base of B"?

c++ - 尝试创建 100MB 的缓冲区时出现段错误

在 cygwin 中使用 C++ 的 QT

c++ - Qt 模型- View - Controller

linux - 使用 qprocess 在 linux 中运行外部应用程序

c++ - 如何在不使用委托(delegate)的情况下在 QML 中显示模型数据

c++ - 内存泄漏是如何发生的?

c++ - 我应该如何以相反的顺序遍历 C++ 容器的元素?

c++ - 编译器如何为虚函数调用生成代码?

android - Qt/QML SwipeDelegate 在移动设备(Android、iOS)上无法正常工作