2014. 6. 20. 14:46

함수가 클래스의 멤버함수인 경우,

 const키워드를 뒤에 삽입가능한데,

이경우 함수에 속해있는 객체의 멤버변수를 변경할 수 없다.


#include <iostream>


using std::endl;

using std::cout;


class Counter

{

    int val;

public:

    Counter()

    {

        val = 0;

    }

    void Print() const

    {

        val = 1; //Error

        ocut << val << endl;

    }


};



int main()

{

    Counter cnt;

    cnt.Print();


    return 0;

}

$ gcc.sh 4-6-1.cpp

4-6-1.cpp: In member function ‘void Counter::Print() const’:

4-6-1.cpp:16: error: assignment of data-member ‘Counter::val’ in read-only structure

4-6-1.cpp:17: error: ‘ocut’ was not declared in this scope



Posted by Triany