12.12 Const class objects and member functions

주홍영·2022년 3월 17일
0

Learncpp.com

목록 보기
136/199

https://www.learncpp.com/cpp-tutorial/const-class-objects-and-member-functions/

다른 object 처럼 class 또한 const로 declaration할 수 있다
만약 const로 만들어진 클래스 object가 member variable에 읽어오는 것은 문제가 없으나
수정하려고 한다면 컴파일 에러가 발생한다
그리고 member function의 경우 호출하면 컴파일 에러가 발생한다

이럴때 우리는 const member function을 이용해 사용한다

#include <iostream>

class Date
{
private:
    int m_year {};
    int m_month {};
    int m_day {};

public:
    Date(int year, int month, int day)
    {
        setDate(year, month, day);
    }

    void setDate(int year, int month, int day)
    {
        m_year = year;
        m_month = month;
        m_day = day;
    }

    int getYear() { return m_year; }
    int getMonth() { return m_month; }
    int getDay() { return m_day; }
};

// note: We're passing date by const reference here to avoid making a copy of date
void printDate(const Date& date)
{
    std::cout << date.getYear() << '/' << date.getMonth() << '/' << date.getDay() << '\n';
}

int main()
{
    Date date{2016, 10, 16};
    printDate(date);

    return 0;
}

위의 코드를 보면 const member function이 아니다
따라서 printDate는 const reference로 argument를 받아오기 때문에
date.getYear()와 같은 member function을 호출하면 컴파일 에러가 발생한다

class Date
{
private:
    int m_year {};
    int m_month {};
    int m_day {};

public:
    Date(int year, int month, int day)
    {
        setDate(year, month, day);
    }

    // setDate() cannot be const, modifies member variables
    void setDate(int year, int month, int day)
    {
        m_year = year;
        m_month = month;
        m_day = day;
    }

    // The following getters can all be made const
    int getYear() const { return m_year; }
    int getMonth() const { return m_month; }
    int getDay() const { return m_day; }
};

위 에서 getYear(), getMonth(), getDay()를 보면 parameter section과 body 사이에
const 키워드가 있다. 이게 const member function을 설정하는 것이다
이렇게 설정된 const member function은 object가 const 타입이여도
호출할 수 있다

Overloading const and non-const function

흔히 사용하지는 않지만 member function에 const와 non-const 버젼을 overload할 수 있다

#include <string>

class Something
{
private:
    std::string m_value {};

public:
    Something(const std::string& value=""): m_value{ value } {}

    const std::string& getValue() const { return m_value; } // getValue() for const objects (returns const reference)
    std::string& getValue() { return m_value; } // getValue() for non-const objects (returns non-const reference)
};

int main()
{
	Something something;
	something.getValue() = "Hi"; // calls non-const getValue();

	const Something something2;
	something2.getValue(); // calls const getValue();

	return 0;
}

참고로 const member function에서 member variable을 수정하려고 하면
컴파일 에러가 발생한다!!

profile
청룡동거주민

0개의 댓글