Post List

[C++] const keyword에 대해서

 C++ 기본 문법을 공부하며 느낀 점을 기록합니다.

const 변수에 대해서는 간단하므로 차치하고, const 함수에 대해 기록합니다.


함수 매개변수 뒤에 const 키워드가 붙은 경우

일반 클래스에서 const 함수 호출

 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>

class Person
{
public:
    int a;
    const int b;
    Person() : b(5)
    {
        a = 3;
    }
    void Func() const
    {
        std::cout << "Func called" << std::endl;
    }

    void Func2()
    {
        std::cout << "Func2 called" << std::endl;
    }
};

int main()
{
    Person person;    // 일반 클래스는 const함수, 일반 함수 모두 호출 가능
    person.Func();
    person.Func2();    
    return 0;
}


const 클래스 객체에서 const함수 호출

 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>

class Person
{
public:
    int a;
    const int b;
    Person() : b(5)
    {
        a = 3;
    }
    void Func() const
    {
        std::cout << "Func called" << std::endl;
    }

    void Func2()
    {
        std::cout << "Func2 called" << std::endl;
    }
};

int main()
{
    const Person person;
    person.Func();
    person.Func2();    // const 객체에서는 일반 함수를 부를 수 없음
    return 0;
}


const 함수 내에서 일반 멤버 변수 호출

 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
#include <iostream>

class Person
{
public:
    int a;
    const int b;
    Person() : b(5)
    {
        a = 3;
    }
    void Func() const
    {
        std::cout << "Func called" << std::endl;
        a = 3;    // const 함수 내에서는 일반 멤버 변수 사용 불가
        b = 1;    // const 멤버변수는 수정 불가
    }

    void Func2()
    {
        std::cout << "Func2 called" << std::endl;
    }
};

int main()
{
    const Person person;
    person.Func();
    return 0;
}

위 세가지 케이스에 대해 알게 되었다.

댓글