在我的BigInt实现中执行return BigInt(*this) += other;时,吐出错误0xC0000005: Access violation reading location (insert memory location here)并关闭程序。为什么要这样做有帮助吗?对于程序的先前上下文,请转到Copy Constructor Issue C++: "0xC0000005: Access violation writing location 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;

}

最佳答案

您正在通过BigInt的值返回operator+=,这将创建一个副本,并且可能您未指定正确的副本构造函数来处理内部动态分配的内存,因此应返回一个引用:

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

关于c++ - 运算符(operator)重载实现:0xC0000005:访问冲突读取位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33578046/

10-11 04:43