定义了一个bigint类用于计算大数字的加法,具体思路就是将每一位数存储于链表中进行计算
BigInt::BigInt(string str) {
//TODO
Cell *cursor;
start = new Cell;
start->finalDigit = str[str.size()-1] - '0';
start->leadingDigits =NULL;
cursor = start;
for(int i=1; i<str.size(); i++){
Cell *cp = new Cell;
cp->finalDigit = str[str.size()-i-1] - '0';
cursor->leadingDigits = cp;
if(i==str.size()-1){
cp->leadingDigits = NULL;
}
cursor = cp;
}
}
/*
* Implementation notes: BigInt destructor
* ---------------------------------------
* The code for the destructor is similar to that of the other
* classes that contain a linked list. You need to store the
* pointer to the next cell temporarily so that you still have
* it after you delete the current cell.
*/
BigInt::~BigInt() {
//TODO
Cell *cursor = start;
while(cursor != NULL){
Cell *temp = cursor;
cursor = temp->leadingDigits;
delete temp;
}
}
并重载了加法,如下图
BigInt BigInt::operator+(const BigInt & b2) const {
//TODO
Cell *cursor1 = this->start;
Cell *cursor2 = b2.start;
int temp = 0;
string result = "";
Stack<char> reverse_stack;
string final = "";
while(cursor1 != NULL && cursor2 != NULL){
int pos = (cursor1->finalDigit + cursor2->finalDigit + temp)%10;
temp = (cursor1->finalDigit + cursor2->finalDigit + temp)/10;
char c = pos + '0';
result += c;
cursor1 = cursor1->leadingDigits;
cursor2 = cursor2->leadingDigits;
}
while(cursor1 != NULL) {
int pos = (cursor1->finalDigit + temp)%10;
temp = (cursor1->finalDigit+temp)/10;
char c = pos + '0';
result += c;
cursor1 = cursor1->leadingDigits;
}
while(cursor2 != NULL) {
int pos = (cursor2->finalDigit + temp)%10;
temp = (cursor2->finalDigit+temp)/10;
char c = pos + '0';
result += c;
cursor2 = cursor2->leadingDigits;
}
if(temp != 0){
result += (temp + '0');
}
for(int i=0; i<result.size(); i++){
reverse_stack.push(result[i]);
}
while(!reverse_stack.isEmpty()){
final += reverse_stack.pop();
}
BigInt r = BigInt(final);
return r;
}
这样使用是没有问题的
但按下面的方式使用就会使程序强制终止
请问是为什么呢?