gpt4 book ai didi

c++ - 运算符重载实现 : 0xC0000005: Access violation reading location

转载 作者:行者123 更新时间:2023-11-28 05:59:21 25 4
gpt4 key购买 nike

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

}

最佳答案

您正在从 operator+= 按值返回 BigInt,这会创建一个拷贝,并且您可能没有指定一个正确的复制构造函数来处理或内部动态分配的内存,你应该返回一个引用:

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

关于c++ - 运算符重载实现 : 0xC0000005: Access violation reading location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33578046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com