我最近一直在学习重载运算符,很快就来到了重载运算符。我尝试了一些例子,但无法真正理解格式及其运作方式。好吧,如果你能用更简单的术语解释代码,那会很有帮助,因为我是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 :(得分: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 :(得分:1)
关于这个主题的好读物是:What is the copy-and-swap idiom?
您的对象包含已分配的内存,因此每次复制对象时,还需要执行新的内存分配,并复制分配的内容。这就是为什么你需要复制构造函数中的那些东西。当编译器尝试复制对象(例如跨函数调用)时,如果将对象放入容器中,则会自动调用复制构造函数。
赋值运算符存在缺陷,因为它需要做更多或更少的操作。它用于
tnp = pnt;
因为它正在处理将一个对象分配给另一个对象,所以它需要使用现有的已分配内存,或者在复制pnt内存之前处理旧tnp对象中内存的释放。