728x90
const객체와 const 객체의 특성들
변수를 상수화 하듯이 객체도 상수화 할 수 있다.
객체에 const 선언이 붙게 되면, 이 객체를 대상으로는 const 멤버 함수만 호출이 가능하다.
#include <iostream>
using namespace std;
class SoSimple {
private:
int num;
public:
SoSimple(int n) : num(n)
{ }
SoSimple& AddNum(int n) {
num += n;
return *this;
}
void ShowData() const {
cout << "num: " << num << endl;
}
};
int main(void) {
const SoSimple obj(7);//const 객체 생성
//obj.AddNum(20);//AddNum은 const함수가 아니기 때문에 호출 불가능
obj.ShowData();
//ShowData는 const함수이기 때문에 const 객체를 대상으로 호출 가능
return 0;
}
멤버변수에 저장된 값을 수정하지 않는 함수는 가급적 const로 선언해서
const객체에서도 호출이 가능하도록 할 필요가 있다.
const함수와 오버로딩
const의 선언 유무도 함수 오버로딩의 조건에 해당된다.
void SimpleFunc() { ... }
void SimpleFUnc() const { ... }
#include <iostream>
using namespace std;
class SoSimple {
private:
int num;
public:
SoSimple(int n) : num(n)
{ }
SoSimple& AddNum(int n) {
num += n;
return *this;
}
void SimpleFunc() {
cout << "SimpleFunc: " << num << endl;
}
void SimpleFunc() const {
cout << "const SimpleFunc: " << num << endl;
}
};
void YourFunc(const SoSimple& obj) {
//전달되는 인자를 const 참조자로 받는다.
//obj1도 인자로 전달 될 수는 있다. 참조자 obj를 통해서 전달받은 객체를 변경하는것이 불가능할 뿐이다.
obj.SimpleFunc();//17행의 const 멤버 함수 호출
}
int main(void) {
SoSimple obj1(2);//일반 객체 생성
const SoSimple obj2(7);//const 객체 생성
obj1.SimpleFunc();//14행의 일반 멤버 함수 호출
obj2.SimpleFunc();//17행의 const 멤버 함수 호출
YourFunc(obj1);
YourFunc(obj2);
return 0;
}
728x90
'공부 > C++' 카테고리의 다른 글
[C++] 6-3. c++에서의 static (2) | 2024.11.01 |
---|---|
[C++] 6-2. 클래스와 함수에 대한 friend 선언 (0) | 2024.10.31 |
[C++] 5-3. 복사생성자의 호출 시점 (0) | 2024.10.31 |
[C++] 5-2. 깊은 복사와 얕은 복사 (0) | 2024.10.31 |
[C++] 5-1. 복사 생성자 (0) | 2024.10.30 |