최근에 오버로드 된 연산자를 배우고 곧 오버로드 된 복사 연산자가 발생했습니다. 몇 가지 예제를 시도했지만 실제로 형식을 이해할 수 없었습니다. 글쎄, 내가 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