Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
05-16 20:20
관리 메뉴

nomad-programmer

[Programming/C++] const 멤버 함수와 비 const 멤버 함수 본문

Programming/C++

[Programming/C++] const 멤버 함수와 비 const 멤버 함수

scii 2023. 1. 19. 15:47

const 멤버 함수는 멤버 함수 내에서 객체의 멤버 변수를 변경하지 않는다는 것을 보장하는 함수이다.

따라서 const 객체는 const 멤버 함수만 호출할 수 있다. const 멤버 함수에서 멤버 변수를 변경하면 컴파일 에러가 발생한다. 사실 자신의 멤버를 변경하지 않는 멤버 함수는 모두 const 멤버 함수여야만 한다.

다음은 cosnt 멤버 함수 예제이다.

class Point{
public:
    Point(int _x=0, int _y=0) : x(_x), y(_y) {}
    int GetX() const { return x; }
    int GetY() const { return y; }
    void SetX(int _x) { x = _x; }
    void SetY(int _y) { y = _y; }
    void Print() const {
        cout << x << ", " << y << endl;
    }

private:
    int x;
    int y;
};

int main(){
    // const 객체. 모든 멤버 변경 불가
    const Point p1(0, 0);

    // 비 const 객체
    Point p2(2, 3);

    p1.Print();
    p2.Print();

    cout<<"p1: "<<p1.GetX()<<" "<<p1.GetY()<<endl;
    cout<<"p2: "<<p2.GetX()<<" "<<p2.GetY()<<endl;

    // error, const 객체는 const 멤버 함수만 호출 가능
    p1.SetX(5);
    p1.SetY(3);

    // 변경 가능
    p2.SetX(1);
    p2.SetY(2);

    return 0;
}

p1은 앞으로 SetX()와 SetY() 멤버 함수는 호출할 수 없다. 두 멤버 함수는 비 const 멤버 함수이므로 const 객체 p1은 비 const 멤버 함수를 호출할 수 없다.

Comments