nakka soft world !

상수 멤버 함수 (const member function) 본문

프로그래밍언어/C++

상수 멤버 함수 (const member function)

nakka 2017. 3. 19. 00:34
728x90

상수 멤버 함수 (const member function)


1. 개요

class Point

{

private:

int x, y;

public :

Point(int a = 0, int b = 0) : x(a), y(b) {}


void set(int a, int b)

{

x = a;

y = b;

}

void print() const   // 상수 멤버 함수 - 모든 멤버를 상수 취급 하는 함수

{

x = 10;  // error

cout << x << ", " << y << endl;   // ok.

}

};



안전성을 향상시키기 위해서 상수 함수를 쓴다는 거는 잘못된 이야기.


class Point

{

public :

int x, y;


Point(int a = 0, int b = 0) : x(a), y(b) {}


void set(int a, int b)

{

x = a;

y = b;

}

void print() // const

};

int main()

{

const Point p(1 ,1);

p.x = 10;   // error

p.set(10, 10);   // error

p.print(); // 값을 바꿀지 안바꿀지 컴파일러는 모름.  // error. 되게 하려면 print()함수는 상수 멤버 함수가 되어야 함. 아래처럼 수정되면 OK

// void print() const { cout << x << ", " << y << endl; }

// 핵심. 상수 객체는 상수 멤버 함수만 호출한다.

}


class Rect

{

private:

int x, y, w, h;

public:

Rect(int a, int b, int c, int d) : x(a), y(b), w(c), h(d) {}

int getArea() const { return w * h; } // get으로 시작하는 함수들은 대부부누 상태를 바꾸지 않고 값을 꺼내는 용도 이기 떄문에 반드시 상수 함수로 만들어야 한다.

// 상수 멤버함수는 상수 객체를 고려한다면 반드시 필요합니다. getter 함수는 반드시 상수함수가 되어야 합니다.

};


void foo(Rect r) // call by value : 객체의 복사본 때문에 메모리 부담

void foo(const Rect& r)

{

int n = r.getArea(); // ???

}


int main()

{

Rect r(1, 1, 10, 10)

int n = r.getArea();

foo(r);

}







728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

연산자 재정의 개념  (0) 2017.03.19
this  (0) 2017.03.19
정적 멤버 데이터 (static member data)  (0) 2017.03.17
Object Copy  (0) 2017.03.17
복사 생성자 (Copy Constructor)  (0) 2017.03.17
Comments