Menu
Coddy logo textTech

상수 멤버 함수

Coddy C++ 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 104개 중 29번째.

이전 레슨에서 getter 메서드에 사용된 const 키워드를 살펴보았습니다. 그런데 함수의 매개변수 목록 뒤에 const가 나타나면 정확히 무엇을 의미할까요? const 멤버 함수는 객체의 어떤 멤버 변수도 수정하지 않겠다고 약속합니다.

class Rectangle {
    int width;
    int height;
public:
    Rectangle(int w, int h) : width(w), height(h) {}
    
    int getArea() const {      // const 멤버 함수
        return width * height;  // 멤버 읽기가 허용됨
    }
    
    void setWidth(int w) {     // Non-const - 객체를 수정함
        width = w;
    }
};

매개변수 목록 뒤의 const는 컴파일러에 다음과 같이 알립니다. "이 function은 객체의 상태를 변경하지 않습니다." const function 내부에서 member 변수를 수정하려고 하면 컴파일러가 오류를 발생시킵니다.

이는 const 객체 또는 const 참조로 작업할 때 필수적입니다. const 객체는 const 멤버 함수만 호출할 수 있습니다:

void printArea(const Rectangle& rect) {
    std::cout << rect.getArea();    // OK - getArea()는 const입니다
    // rect.setWidth(10);           // ERROR - setWidth()는 const가 아닙니다
}

객체를 수정하지 않는 함수를 const로 표시하는 것은 좋은 관행입니다. 이는 의도를 문서화하고, 함수가 const 객체와 함께 작동할 수 있도록 하며, 컴파일러가 실수로 인한 수정을 발견하는 데 도움이 됩니다. 데이터를 읽기만 하는 모든 멤버 함수는 const로 표시해야 합니다.

challenge icon

챌린지

쉬움

const 멤버 함수를 언제, 왜 사용해야 하는지 보여 주는 온도 변환기를 만들어 보겠습니다. 일부 메서드는 데이터만 읽으므로 const여야 하고, 다른 메서드는 객체의 상태를 수정하는 클래스를 만들게 됩니다.

코드를 구성하기 위해 두 개의 파일을 만듭니다.

  • Temperature.h: 온도 값을 저장하고 이를 읽고 수정하는 다양한 방법을 제공하는 Temperature 클래스를 정의합니다. 클래스에는 다음이 포함되어야 합니다.
    • 온도를 저장하는 private 멤버 celsius(double)
    • initial Celsius 값을 받는 Constructor
    • 저장된 값을 반환하는 getCelsius() 메서드. 이 메서드는 데이터만 읽으므로 const여야 합니다.
    • celsius * 9.0 / 5.0 + 32.0 Formula를 사용해 온도를 Fahrenheit로 계산하여 반환하는 getFahrenheit() 메서드. 아무것도 수정하지 않으므로 역시 const여야 합니다.
    • celsius + 273.15를 사용해 온도를 Kelvin으로 반환하는 getKelvin() 메서드. 이 메서드도 const여야 합니다.
    • 저장된 온도를 업데이트하는 setCelsius(double value) 메서드. 객체를 수정하므로 const일 수 없습니다.
    • delta를 현재 온도에 더하는 adjustBy(double delta) 메서드. 이 메서드도 non-const입니다.
  • main.cpp: 일반 객체와 const 객체에서 const 멤버 함수가 어떻게 작동하는지 보여 줍니다. input에서 initial 온도 값을 읽은 다음 다음을 수행합니다.
    • input 값으로 Temperature 객체를 Create합니다.
    • "Initial: <celsius>C = <fahrenheit>F = <kelvin>K"를 출력합니다.
    • 온도를 10.0 degrees만큼 Adjust합니다.
    • "After adjustment: <celsius>C"를 출력합니다.
    • const reference를 받고 "Reading: <celsius>C, <fahrenheit>F"를 출력하는 Helper function void printReadings(const Temperature& temp)를 만듭니다. 이 function은 temp에 대해 const methods만 Call할 수 있습니다.
    • 온도 객체를 사용하여 printReadings()를 Call합니다.
    • 온도를 0.0(freezing point)으로 설정합니다.
    • "Freezing point: <celsius>C = <fahrenheit>F"를 출력합니다.

<iomanip>std::fixedstd::setprecision(1)을 사용하여 모든 온도 값을 소수점 첫째 자리까지 Format합니다.

여기서 핵심은 printReadings()가 const reference를 받으므로 const로 표시된 methods만 Call할 수 있다는 점입니다. 따라서 getter methods를 const로 올바르게 표시하는 것이 중요합니다. 이를 통해 객체를 수정할 수 없는 context에서도 해당 methods를 사용할 수 있습니다.

직접 해보기

#include <iostream>
#include <iomanip>
#include "Temperature.h"
using namespace std;

// TODO: 여기에 Temperature 클래스 메서드를 구현하세요
// 생성자
Temperature::Temperature(double initialCelsius) {
    // TODO: celsius를 초기화하세요
}

// TODO: getCelsius()를 const로 구현하세요

// TODO: getFahrenheit()를 const로 구현하세요

// TODO: getKelvin()를 const로 구현하세요

// TODO: setCelsius(double value)를 구현하세요

// TODO: adjustBy(double delta)를 구현하세요


// TODO: const Temperature&를 받는 헬퍼 함수 printReadings를 만드세요 
// 그리고 "Reading: <celsius>C, <fahrenheit>F"를 출력합니다
// Note: 이 함수는 temp에 대해 const 메서드만 호출할 수 있습니다!


int main() {
    double initialTemp;
    cin >> initialTemp;

    // 출력 형식 설정
    cout << fixed << setprecision(1);

    // TODO: 입력 값으로 Temperature 객체를 생성하세요

    // TODO: "Initial: <celsius>C = <fahrenheit>F = <kelvin>K"를 출력하세요

    // TODO: 온도를 10.0도만큼 조정하세요

    // TODO: Print "After adjustment: <celsius>C"

    // TODO: temperature 객체로 printReadings()를 호출하세요

    // TODO: Set the temperature to 0.0 (freezing point)

    // TODO: Print "Freezing point: <celsius>C = <fahrenheit>F"

    return 0;
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러