본문 바로가기

카테고리 없음

[C++]멤버 초기화 리스트를 사용 - 인자의 사용




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
 
#include <iostream>
using namespace std;
 
class NeedConstructor
{
public:
    const int maxCount;
    int& ref;
    int sample;
 
    NeedConstructor();
    NeedConstructor(int count, int& number);
// 두개의 인자가 있는 생성자 추가
 
};
 
NeedConstructor::NeedConstructor(int count, int& number)// 두개의 인자가 있는 생성자 추가
    : maxCount(count), ref(number)
{
    sample = 200;
}
 
NeedConstructor::NeedConstructor()
    : maxCount(100), ref(sample)
{
    sample = 200;
}
 
int main()
{
    // 참조할 변수를 준비한다.
    int number = 400;
 
    // 객체를 생성한다.
    NeedConstructor  cr(300, number);
 
    // 내용을 출력한다.
    cout << "cr.maxCount = " << cr.maxCount << "\n";
    cout << "cr.ref = " << cr.ref << "\n";
 
    return 0;
}
 
cs


실행 결과

cr.maxCount = 300

cr.ref = 400