프로그래밍/C++

C++ 문법 - 생성자

게으른구름 2018. 1. 22. 00:02

< 생성자 >


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
#include <iostream>
 
using namespace std;
 
int i_start = 1;
 
class Test
{
public:
    int number = 0;
    Test()
    {
        cout << "생성자" << endl;
        if (i_start == 1)
        {
            number += 100;
        }
    }
};
 
int main()
{
    cout << "시작" << endl;
    Test first;
    cout << "number : " << first.number << endl;
    return 0;
}
 
cs


클래스명과 같은 이름의 특별한 메소드입니다.

객체를 생성할 때 실행됩니다.


주로 멤버 변수 초기화를 위해 사용합니다.


for 반복문의 초기화 부분과 연관지어 생각해보세요.

1
for (int i = 0 (이부분); i < 10; i++)
cs