반응형
shalloew copy
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#include <iostream>
using namespace std;
/*
복사 생성자 호출 시기
1.객체 생성시 객체를 인자로 줄 경우
2.객체 생성시 객체를 대입 할 경우
3.매소드의 매개변수로 객체를 선언할 경우
4.메소드에서 객체를 리턴할 경우
*/
class A{
int a;
int b;
//생성자
public:
A(int a = 0) {
this->a = a;
this->b = a;
}
//소멸자
//복사생성자
A(A &r) {
this->a = r.a; // 뒤의 a는 aa의 a
//this의 a는 bb객체의 a
//default로 해결
}
//대입연산자
int getA()const {
return a;
}
int getB()const {
return b;
}
};
void main() {
A aa(90);
cout << aa.getA() << aa.getB() << endl;
A bb(aa); //복사생성자호출
cout << bb.getA() << aa.getB() << endl;
}
// 얕은 복사 : 쉽게 다시 말해 - 필트를 포인터 사용 안했을때 사용가능
// 깊은 복사 : 누가 하느냐? -개발자가 한다
// 얕은, 깊은 복사 목적 : 필드(멤버변수) 복사
|
cs |
deep copy
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
#include <iostream>
using namespace std;
class A {
int *a;
int *b;
public:
//생성자
A(int a = 0) {
this->a = new int;
this->b = new int;
*(this->a) = a;
*(this->b) = a;
}
//소멸자
~A() {
delete a;
delete b;
}
//복사생성자
A(const A &r) {//A를 읽기만 함
//*(t.a) =1000;
this->a = new int;
this->b = new int;
*(this->a) = *(r.a); // 뒤의 a는 aa의 a
//this의 a는 bb객체의 a
//default로 해결
*(this->b) = *(r.b); //멤버니까 접근허용 but const 읽기만 허용
cout << "생";
}
int getA()const {
return *a;
}
int getB()const {
return *b;
}
//대입연산자
};
void main() {
A aa(90);
cout << aa.getA() << aa.getB() << endl;
A bb(aa); //복사생성자호출
cout << bb.getA() << aa.getB() << endl;
}
|
cs |
반응형