C++의 Const 멤버 함수
상수 멤버 함수는 해당 클래스의 데이터 멤버 값을 변경할 수 있는 권한이 거부된 함수입니다. 멤버 함수를 상수로 만들기 위해 const 키워드를 함수 프로토타입과 함수 정의 헤더에 추가합니다.
멤버 함수 및 멤버 함수 인수와 마찬가지로 클래스의 객체도 const로 선언할 수 있습니다. const로 선언된 객체는 수정할 수 없으므로 const 멤버 함수만 호출할 수 있습니다. 이러한 함수는 객체를 수정하지 않도록 보장합니다. const 객체는 객체 선언 앞에 const 키워드를 붙여 생성할 수 있습니다. const 개체의 데이터 멤버를 변경하려고 하면 컴파일 타임 오류가 발생합니다.
통사론
const 멤버 함수는 세 가지 방법으로 정의할 수 있습니다.
1. 클래스 내에서 함수를 선언하는 경우.
return_type function_name () const ;
예:
int get_data() const;
2. 클래스 선언 내 함수 정의의 경우.
return_type function_name () const { //function body } 예:
int get_data() const { //function body } 3. 클래스 외부의 함수 정의용.
return_type class_name::function_name () const { //function body } 예:
int Demo :: get_data() const { } 중요사항
- 함수가 const로 선언되면 모든 유형의 객체, const 객체는 물론 const가 아닌 객체에서도 호출될 수 있습니다.
- 객체가 const로 선언될 때마다 선언 시 초기화되어야 합니다. 그러나 선언하는 동안 객체 초기화는 생성자의 도움을 통해서만 가능합니다.
- 함수 선언에 const 키워드가 사용되면 함수는 const가 됩니다. const 함수의 개념은 호출된 객체를 수정하는 것을 허용하지 않는다는 것입니다.
- 실수로 객체가 변경되는 것을 방지하려면 가능한 한 많은 함수를 const로 만드는 것이 좋습니다.
Const 멤버 함수의 예
실시예 1
아래 C++ 프로그램은 상수가 아닌 멤버 함수에서 데이터 멤버를 업데이트할 수 있음을 보여줍니다.
C++
// C++ program to demonstrate that data members can be> // updated in a member function that is not constant.> #include> using> namespace> std;> class> Demo {> > int> x;> public> :> > void> set_data(> int> a) { x = a; }> > // non const member function> > // data can be updated> > int> get_data()> > {> > ++x;> > return> x;> > }> };> main()> {> > Demo d;> > d.set_data(10);> > cout < < d.get_data();> > return> 0;> }> |
산출
11
실시예 2
아래 C++ 프로그램은 Constant 멤버 함수에서 데이터를 업데이트할 수 없음을 보여줍니다.
C++
// C++ program to demonstrate that data cannot be updated> // in a Constant member function> #include> using> namespace> std;> class> Demo {> > int> x;> public> :> > void> set_data(> int> a) { x = a; }> > // constant member function> > int> get_data()> const> > {> > // Error while attempting to modify the data> > // member> > ++x;> > return> x;> > }> };> main()> {> > Demo d;> > d.set_data(10);> > cout < < endl < < d.get_data();> > return> 0;> }> |
산출
./Solution.cpp: In member function 'int Demo::get_data() const': ./Solution.cpp:17:11: error: increment of member 'Demo::x' in read-only object ++x; ^
실시예 3
아래 C++ 코드는 클래스 정의 외부에서 상수 멤버 함수를 정의하는 방법을 보여주고 전용 멤버 변수의 값을 설정하고 검색하기 위한 상수 멤버 함수의 사용법을 보여줍니다.
C++
// Constant member function defined outside the class> #include> using> namespace> std;> class> Demo {> > int> x;> public> :> > void> set_data(> int> );> > // const member function> > int> get_data()> const> ;> };> // Function definition for setting the value of x.> void> Demo::set_data(> int> a) { x = a; }> // Function definition for retrieving the value of x (const> // member function).> int> Demo::get_data()> const> {> return> x; }> main()> {> > Demo d;> > // Set the value of x to 10 using the non-const member> > // function.> > d.set_data(10);> > // Print the value of x using the const member function.> > cout < < d.get_data();> > return> 0;> }> |
산출
10
실시예 4
아래 C++ 프로그램은 const 함수가 const가 아닌 개체에 의해 호출될 수 있음을 보여줍니다.
C++
// C++ program to demonstrate that const functions can be> // called by non const objects> #include> using> namespace> std;> class> Test {> > int> value;> public> :> > Test(> int> v = 0) { value = v; }> > // const member function> > int> getValue()> const> {> return> value; }> };> int> main()> {> > // non const object> > Test t(20);> > cout < < t.getValue();> > return> 0;> }> |
산출
20
함수가 const로 선언되면 모든 유형의 객체에서 호출될 수 있습니다. non-const 함수는 non-const 객체에 의해서만 호출될 수 있습니다.
예를 들어 다음 프로그램에는 컴파일러 오류가 있습니다.
C++
// C++ program that demonstrate that non-const functions can> // not be called by const objects> #include> using> namespace> std;> class> Test {> > int> value;> public> :> > Test(> int> v = 0) { value = v; }> > // non const member function> > int> getValue() {> return> value; }> };> int> main()> {> > // const object> > const> Test t;> > cout < < t.getValue();> > return> 0;> }> |
산출
./d869c7ba-f199-4a67-9449-3936b5db4c5b.cpp: In function 'int main()': ./d869c7ba-f199-4a67-9449-3936b5db4c5b.cpp:14:24: error: passing 'const Test' as 'this' argument of 'int Test::getValue()' discards qualifiers [-fpermissive] cout < < t.getValue();
또 다른 예를 살펴보겠습니다.
C++
// Demonstration of constant object,> // show that constant object can only> // call const member function> #include> using> namespace> std;> class> Demo {> > int> value;> public> :> > Demo(> int> v = 0) { value = v; }> > void> showMessage()> > {> > cout < <> 'Hello World We are Tushar, '> > 'Ramswarup, Nilesh and Subhash Inside'> > ' showMessage() Function'> > < < endl;> > }> > // const member function> > void> display()> const> > {> > cout < <> 'Hello world I'm Rancho '> > 'Baba Inside display() Function'> > < < endl;> > }> };> int> main()> {> > // Constant object are initialised at the time of> > // declaration using constructor> > const> Demo d1;> > // d1.showMessage();Error occurred if uncomment.> > d1.display();> > return> (0);> }> |
산출
Hello world I'm Rancho Baba Inside display() Function
Const 멤버 함수에 대한 FAQ
Q1. 클래스의 const 객체가 const가 아닌 멤버 함수를 호출할 수 있나요?
답변:
아니요, const로 선언된 객체는 수정할 수 없으므로 const 멤버 함수만 호출할 수 있습니다. 이러한 함수는 객체를 수정하지 않도록 보장하기 때문입니다.
Q2. 클래스의 비-const 객체가 const 멤버 함수를 호출할 수 있나요?
답변:
함수가 const로 선언되면 모든 유형의 객체에서 호출될 수 있습니다.