Updated:

less than 1 minute read

const 멤버 함수

  • 읽기만 수행하는 함수


코드

#include <iostream>

using namespace std;

class Test {
    private:
        int i = 0;

    public:
        Test() = default;
        ~Test() = default;

        void show1() const { cout << this->i << endl; }
        void Show2() const {
            this->i = 1;
            cout << this->i << endl;
        }
};

int main() { return 0; }


실행 결과

test.cpp: In member function ‘void Test::Show2() const’:
test.cpp:15:33: error: assignment of member ‘Test::i’ in read-only object
   15 |                         this->i = 1;
      |                         ~~~~~~~~^~~