본문 바로가기
카테고리 없음

C++ copy constructor(얕은복사, 깊은복사)

by 리승연 2018. 9. 21.
반응형

복사생성자 호출 시기

 

1. 객체 생성시 객체를 인자로 줄 경우

 

2. 객체 생성시 객체를 대입 할 경우

 

3. 메소드의 매개변수로 객체를 선언 할 경우

 

4. 메소드에서 객체를 리턴할 경우

 

 

 

A aa;

 

A bb(aa);

 

A cc=aa;

 

void A:disp(A aa){

 

A aa;

 

return aa;

 

}

 

 

 

복사생성자는 필드를 복사하는 것

 

 

 

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
#include <iostream>
using namespace std;
class A{
    int a;
    int b;
public:
    A(int a = 0) {
        this->= a;
        this->= a;
    }
    
    A(A &r) { //복사생성자
        this->= 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
#include <iostream>
using namespace std;
 
class A {
    int *a;
    int *b;
    
public:
    //생성자
    A(int a = 0) {
        this->= new int;
        this->= new int;
    
        *(this->a) = a;
        *(this->b) = a;
        
    }
    //소멸자        
    ~A() {
            delete a;
            delete b;
    }
    
    //복사생성자
    A(const A &r) {//A를 읽기만 함.const 사용
        
        this->= new int;
        this->= 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

 

반응형