Language/C++

[C++] 11.Unmanaged Programming: Const flag

coco_daddy 2024. 1. 25. 12:53

Vector 클래스의 멤버 함수

// Vector.h

class Vector
{
public:
    void SetX(int x);
    void SetY(int y);
    int GetX() const;
    int GetY() const;
    void Add(const Vector& other);
private:
    int mX;
    int mY;
};

const의 의미

  • 바꿀 수 없음.
// const 변수
const int LINE_SIZE = 20;
LINE_SIZE = 10; // compile error

// const 메서드
int GetX() const;

method란?

  • 오브젝트 안의 클래스 안의 함수를 method라고 부른다.
  • 그 안에 포함되지 않는 전역 함수를 함수라고 부른다.
  • 이 둘은 혼용되기도 하며, 신경 쓰지 않아도 된다.

const method

  • 오브젝트 안에 들어가는 함수에 붙는 const.
  • GetX()는 int를 반환하지만, 이 int의 값은 변경할 수 없다.

const 멤버 함수

  • 멤버 변수가 변하는 것을 방지한다
int GetX() const
{
    return mX; // 문제 없음.
}

void AddConst(const Vector& other) const
{
    mX = mX + other.mX; // compile error
    mY = mY + other.mY; // compile error
}
  • AddConstother의 값을 바꾸려고 하기 때문에 컴파일 에러가 발생한다.

const를 기본적으로 모두 달고 있는 것이 안전하다.

  • 제한적으로 코드를 작성해야 함.
  • 방어적 프로그래밍!