我最近一直在學習重載運算符,很快就來到了超載複製運算符。我嘗試了一些例子,但無法真正理解格式及其功能。那麼,如果你能以更簡單的方式向我解釋代碼,這將是有幫助的,因爲我是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;
}
感謝您的時間
請用不太冒犯祖母的東西替換名字'廢話'。 –
@ Cheersandhth.-Alf http://www.amazon.com/Everyone-Turtleback-Library-Binding-Edition/dp/0613685725 – Potatoswatter
@ Cheersandhth.-Alf對不起,我實際上只是遵循TheNewBoston風格。 – Jim