c++ - 重载复制赋值运算符

标签 c++ class oop operator-overloading

我最近在学习重载运算符,很快就接触到了重载复制运算符。我尝试了一些示例,但无法真正理解其格式及其功能。好吧,如果您能用更简单的术语向我解释代码,那将会很有帮助,因为我是 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;
        }

感谢您的宝贵时间

最佳答案

复制赋值运算符可以使用对象已拥有的现有资源。它不像构造函数。 (您的复制构造函数是正确的。)

//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;
}

关于c++ - 重载复制赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22162897/

相关文章:

c++ - 复制构造函数中的指针

php - 具有相同类名的命名空间

java - 如何获取特定类中的所有字符串?

来自其他文件的c++类

design-patterns - 进度条设计模式?

java - 我怎样才能实现一个 ActionListener 呢?

java - java如何处理非静态变量?

c++ - Visual Studio 2012 C++ OpenGL GLFW 链接器错误

C++ OpenGL 闪烁问题

c++ - 指向静态成员函数的指针是 "invalid"作为 g++ 的模板参数