깊은 복사 = 값 복사
얕은 복사 = 주소값 복사
문제: 위 코드는 복사 생성자의 얕은 복사로 인하여 두 객체가 이어진 상태이다. 이를 보이지 않는 복사 생성자를 고쳐서 깊은 복사로 만들어보자.
#include <iostream>
using namespace std;
class SelfRef
{
private:
int *num;
public:
SelfRef(int n) : num(new int(n))
{
cout << "객체생성" << endl;
}
void setNumber()
{
*num += 1;
}
void ShowTwoNumber()
{
cout << *num << endl;
}
};
int main(void)
{
SelfRef obj(3);
SelfRef obj2(obj);
obj.setNumber();
obj.ShowTwoNumber();
obj2.ShowTwoNumber();
return 0;
}
답
#include <iostream>
using namespace std;
class SelfRef
{
private:
int* num;
public:
SelfRef(int n) : num(new int(n))
{
cout << "객체생성" << endl;
}
SelfRef(const SelfRef& obj) {
num = new int(*obj.num); //*(obj.num)이거임.. (*obj).num이 아니고..
}
void setNumber()
{
*num += 1;
}
void ShowTwoNumber()
{
cout << *num << endl;
}
};
int main(void)
{
SelfRef obj(3);
SelfRef obj2(obj);
obj.setNumber();
obj.ShowTwoNumber();
obj2.ShowTwoNumber();
return 0;
}
복사생성자(얕은복사)를 이용하라하면..?
#include <iostream>
using namespace std;
class SelfRef
{
private:
int* num;
public:
SelfRef(int n) : num(new int(n))
{
cout << "객체생성" << endl;
}
//모든 디폴트 복사 생성자는 얕은 복사이다. -> 주소 복사
SelfRef(const SelfRef& a) {
num = a.num;
}
void setNumber()
{
*num += 1;
}
void ShowTwoNumber()
{
cout << *num << endl;
}
};
int main(void)
{
SelfRef obj(3);
SelfRef obj2(obj);
obj.setNumber();
obj.ShowTwoNumber();
obj2.ShowTwoNumber();
return 0;
}
'언어 > C++' 카테고리의 다른 글
[C++] for each문 ->참조 변수 언제 사용? (feat.깊은 복사, 얕은복사) (+ cin.fail) 예제 (0) | 2023.09.30 |
---|---|
[C++] locale이란? (0) | 2023.09.29 |
[C++] 1. 멤버이니셜라이저(feat. const 변수), 2. 생성자와 소멸자를 이용한 동적할당, 3. this 포인터 (0) | 2023.09.25 |
[C++] 참조자가 객체로 쓰였을 때는? (0) | 2023.09.25 |
[C++] *this가 반환 값일 때, 함수의 반환형에 &를 쓰는 이유 (+ this와 *this의 차이) (0) | 2023.09.24 |