2014-03-04 115 views
2

我最近一直在學習重載運算符,很快就來到了超載複製運算符。我嘗試了一些例子,但無法真正理解格式及其功能。那麼,如果你能以更簡單的方式向我解釋代碼,這將是有幫助的,因爲我是C++的初學者。反正這裏是我的代碼:重載複製賦值運算符

#include <iostream> 
using namespace std; 

class Point{ 
private: 
    int* lobster; 
public: 
    Point(const int somelobster){ 
     lobster = new int; 
     *lobster = somelobster; 
    } 
    //deep copy 
    Point(const Point& cpy){ //copy of somelobster(just to make sure that it does not do shallow copy) 
     lobster = new int; 
     *lobster = *cpy.lobster; 
    } 
    //assingment operator 
    Point& operator=(const Point& cpy){ //used to copy value 
     lobster = new int; //same thing as the original overloaded constructor 
     *lobster = *cpy.lobster; //making sure that it does not makes a shallow copy when assigning value 
     return *this; 
    } 

    void display_ma_lobster(){ //display nunber 
     cout << "The number you stored is: " << *lobster << endl; 
    } 
    ~Point(){ //deallocating memory 
     cout << "Deallocating memory" << endl; 
     delete lobster; 
    } 
}; 

int main(){ 
    Point pnt(125); 
    cout << "pnt: "; 
    pnt.display_ma_lobster(); 
    cout << "assigning pnt value to tnp" << endl; 
    Point tnp(225); 
    tnp = pnt; 
    tnp.display_ma_lobster(); 
    return 0; 
} 

但真正需要解釋的主要部分是:

//deep copy 
     Point(const Point& cpy){ //copy of somelobster(just to make sure that it does not do shallow copy) 
      lobster = new int; 
      *lobster = *cpy.lobster; 
     } 
     //assingment operator 
     Point& operator=(const Point& cpy){ //used to copy value 
      lobster = new int; //same thing as the original overloaded constructor 
      *lobster = *cpy.lobster; //making sure that it does not makes a shallow copy when assigning value 
      return *this; 
     } 

感謝您的時間

+0

請用不太冒犯祖母的東西替換名字'廢話'。 –

+3

@ Cheersandhth.-Alf http://www.amazon.com/Everyone-Turtleback-Library-Binding-Edition/dp/0613685725 – Potatoswatter

+0

@ Cheersandhth.-Alf對不起,我實際上只是遵循TheNewBoston風格。 – Jim

回答

2

的拷貝賦值運算符可以使用已經擁有的現有資源物體。它不像一個構造函數。 (你的拷貝構造函數是正確的。)

//assingment operator 
Point& operator=(const Point& cpy){ //used to copy value 
    // Do not allocate anything here. 
    // If you were to allocate something, that would require deallocating yer shit too. 

    *crap = *cpy.crap; //making sure that it does not makes a shallow copy when assigning value 
    return *this; 
} 
1

關於這個主題很好看的是:What is the copy-and-swap idiom?

你的對象包含分配的內存,所以每次您複製對象時,您還需要執行一個新的內存分配和複製您的分配內容。這就是爲什麼你需要複製構造函數中的那些東西。當編譯器試圖複製你的對象時,例如通過函數調用,它會自動調用複製構造函數,如果它被放入容器中。

賦值運算符有缺陷,因爲它需要多做一點或少一點。它在

tnp = pnt; 

使用,因爲它處理分配一個對象到另一個,它需要既可以使用現有的分配的內存,或處理的內存釋放舊TNP對象的PNT內存在複製之前。