c++加法重载与类的赋值

定义了一个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;
}

这样使用是没有问题的

img


但按下面的方式使用就会使程序强制终止

img


请问是为什么呢?

你应该定义拷贝构造函数,进行深拷贝。类似于你的有参构造函数,要为start申请新的空间进行数据复制
否则你用result = temp2,是进行的浅拷贝,实际上这两个变量会共用start这个指针变量。当return时,temp2变量会进行析构,从而导致共有的start指针变量被系统回收,导致return 的 result中的start变为野指针,外部一操作这个start就会导致程序崩溃