运算符重载实现:0xC0000005:读取位置存在访问冲突

Operator overloading implementation: 0xC0000005: Access violation reading location

本文关键字:位置 存在 访问冲突 读取 0xC0000005 重载 实现 运算符      更新时间:2023-10-16

当在我的BigInt实现中执行return BigInt(*this) += other;时,会抛出错误0xC0000005: Access violation reading location (insert memory location here),并关闭程序。它为什么这么做有什么帮助吗?对于我的程序的上一个上下文,请转到复制构造函数问题C++:";0xC0000005:访问违规写入位置0x00000000;

BigInt.cpp

// binary addition
BigInt BigInt::operator+(BigInt const& other) const {
    return BigInt(*this) += other;
}
// compound addition-assignment operator
BigInt BigInt::operator+=(BigInt const& other) {
    //return this->data = this->data + other.data;
    //BigInt thisBigInt = *this;
    if (!other.isPositive) {
        //return thisBigInt -= other;
    }
    //possible check for both negative???

    int sum = 0; //holds the sum of the value in both vectors
    int maxSize = 0; //holds size of biggest BigInt
    int carry = 0; //holds carry over value
    int sizeDifference = 0; //holds size difference between b and a if b is bigger
    //check size
    while (bigIntVector->getSize() < other.bigIntVector->getSize()) {
        bigIntVector->resize(); //increase size of first big int until it matches size of second
    }
    if (bigIntVector->getSize() > other.bigIntVector->getSize()) {
        sizeDifference = bigIntVector->getSize() - other.bigIntVector->getSize();
        //cout << "sizeDiff: " << sizeDifference << endl;
    }
    maxSize = bigIntVector->getSize();
    int otherCounter = other.bigIntVector->getSize() - 1; //keeps track if we are done getting digits from other array
    //cout << "otherCounter: " << otherCounter << endl;
    for (int i = maxSize - 1; i >= 0; i--) {
        //cout << "element1: " << bigIntVector.getElementAt(i) << endl;
        //cout << "element2: " << other.bigIntVector.getElementAt(i) << endl;
        sum += bigIntVector->getElementAt(i);
        if (otherCounter >= 0) {
            sum += other.bigIntVector->getElementAt(i - sizeDifference); //move index if size is different
            sum += carry;
            carry = 0;
            //cout << "sum: " << sum << endl;
            if (sum > 9) {
                ++carry;
                bigIntVector->setElementAt(i, sum%base);
            }
            else {
                carry = 0;
                bigIntVector->setElementAt(i, sum%base);
            }
            --otherCounter; //only decrement otherCounter if we have reached 2nd vector elements
        }
        if (otherCounter < 0 && carry > 0) {
            bigIntVector->resize(); //increase size of big int
            bigIntVector->setElementAt(i, carry); //set carry in front of sum spot
        }
        sum = 0;
    }
    return *this;
}

您从operator+=按值返回BigInt,这会创建一个副本,而且您可能没有指定正确的副本构造函数来照顾或内部动态分配的内存,您应该返回一个引用:

BigInt& BigInt::operator+=(BigInt const& other)