2014-03-04 113 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内存在复制之前。