在我的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;
}
答案 0 :(得分:1)
您正在从BigInt
返回值operator+=
,这会创建一个副本,可能您没有指定正确的复制构造函数,它需要注意或内部动态分配内存,您应该返回一个引用:
BigInt& BigInt::operator+=(BigInt const& other)