Program/C,C++

const 멤버 함수

Health&Program 2023. 6. 28. 22:27
class Person
{
private:
    const string _name;
    float _weight;
    float _height;
public:
    Person(const string& name, float weight, float height)
        : _name(name), _weight(weight), _height(height)
    {
    }
    
    float getWeight(/*const Person* this */) const
    {
        return _weight;
    }
};

int main()
{
    const Person person0("Donghee", 84.f, 178.8.f);
    person0.getWeight();
}

Person class의 getWeight에 const 키워드를 붙임으로써 Class 사용자는 Person Class를 Const로 선언하고 해당 멤버함수를 사용할 수 있다.

 

새로 배운 점

1. Class의 멤버함수는 암시적으로 this 포인터를 받는다.

2. Class를 const로 선언하는 사용하는 것을 대비할 때에는 get 함수에 대해 const 키워드를 붙이자.