Typing diary

c++ 복사 생성자 본문

C, C++

c++ 복사 생성자

Jcon 2022. 8. 16. 15:17
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
#include <iostream>
#include <string>
using namespace std;
 
class Circle
{
    int radius;
    char* name;
public:
    Circle() {}
    Circle(Circle& c); //복사 생성자 선언 (선언을 안하더라도 컴파일러에서 디폴트 복사 생성자를 삽입한다.)
};
 
Circle::Circle(Circle & c) //복사 생성자 구현(디폴트 생성자는 얕은 복사를 하기 때문에 복사 생성자를 새로 구현해야 한다.)
{
    //깊은 복사 생성자
    this->radius = c.radius;
    this->name = new char[strlen(c.name) + 1];
    strcpy(this->name, c.name);
}
 
void func(Circle c){}
 
int main()
{
    Circle a;
    //※복사 생성자가 호출 된는 경우 
    Circle b(a);    
    Circle a = b;   //객체로 초기화 하여 객체가 생성될때
    func(b);        //값에 의한 호출로 객체가 전달될때
    
    //Circle func(Circle a) 
    //{ return a; }    함수가 객체를 리턴할떄
}
cs

'C, C++' 카테고리의 다른 글

명품 c++ programming 4장 10번  (0) 2022.08.16
c++ 참조  (0) 2022.08.16
c++ 메모리 동적할당 초기화, 메모리 누수  (0) 2022.08.16
string 문자열  (0) 2022.08.16
명품 c++ programming 4강 Open Challenge  (0) 2022.08.16