void print() const{
// 이러한 형태를 const member function 이라고 한다.
}
함수의 call by value의 경우 복사본 overhead가 발생할 수 있음
class Test{
int a,b;
public:
Test(int a,int b):a{a},b{b}{ }
int get() const {return a+b;}
// #3 그렇기 때문에 이렇게 const member function을 통해 함수를 만들면 된다.
}
//void constFunc(Test t){ // #1 이 경우는 call by value로 overhead가 발생함
void constFunc(const Test& t){ // #2 이렇게 call by reference를 사용하게 되면
int result = t.get()
}
예를들어 객체가 몇번 호출 되었는지 확인하려면 static을 사용한다.
class Test{
int a,b;
public:
Test(int a,int b):a{a},b{b}{ }
int get() const {
static int cnt = 0;
return ++cnt;
}
}
int main(){
Test t1(1,2);
Test t2(1,2);
t1.get();
t2.get();
t1.get();
// 이렇게 호출하면 cnt 값이 1 2 3 이 된다
// 그런데 만약 t1, t2가 각각의 cnt를 가지게 하려면 어떻게 해야할까?
// member data를 사용하면 된다.
// 하지만 이 방법의 경우 const member function에서는 값을 변경할 수 없음
// 이럴 때 사용하는 것이 mutable member data
}
class Test{
int a,b;
mutable int cnt =0;// 이렇게 mutable을 사용하면 가능
public:
Test(int a,int b):a{a},b{b}{ }
int get() const {
// static int cnt = 0;
return ++cnt;
}
}
int main(){
Test t1(1,2);
Test t2(1,2);
t1.get();
t2.get();
t1.get();
}