<const 변수>
변수에 const라는 키워드를 사용하여 상수(constant)의 의미를 갖게 하여 그 내용을 변경할 수 없게 한다.

<const 변수 예제>

#define IN 1 		// 컴파일 전에 IN을 찾아서 1로 바꿈
#include <iostream>
int main()
{
const int x = 2; 	// 변수 x는 항상 1, 변경 불가, 초기값 지정해야
int const y = 3; 	// 비추, const는 자료형 앞에 씀
const int z{4}; 	// Uniform initialization, C++11, z{}
constexpr int a = 5; 	//C++11부터 가능, compile-time constant
std::cout << IN << x << y << z << a;
return 0;
}
실행 결과 : 12345

<const 멤버>
1. const형 멤버함수는 해당 멤버변수를 변경하는 치환 (replacement)연산을 수행할 수 없다.
2. const로 지정된 함수에서는 멤버변수의 값을 변경할 수 없다
3. const함수는 const함수만 호출할 수 있으며 일반 멤버함수에는 접근할 수 없다
4. 생성자와 소멸자에서는 const를 사용할 수 없다
5. const형을 선언하고자 하면 멤버변수는 형 앞에 const를, 멤버함수는 함수의 괄호 다음에 const를 추가한다

<const형 멤버변수와 멤버함수>

class Dog
{
const int age; 		// 멤버변수는 형 앞에 const를 추가
int getAge() const; 	// 멤버함수는 괄호 다음에 const를 추가
};
int Dog::getAge() const // 멤버함수는 괄호 다음에 const를 추가
{
return age;
}
#include <iostream>
class Dog {
	int age; //private 생략함
public:
	int getAge() const;
	void setAge(int a) { age = a; }
	void view() const { std::cout << "나는 view"; }
};
int Dog::getAge() const
{
	view(); 
	return (age); 
}
int main()
{
	Dog happy;
	happy.setAge(5);
	std::cout << happy.getAge();
	return 0;
}

<const 객체>
1. 객체가 const로 지정되면 해당 객체에 초기화된 데이터는 변경할 수 없으며 const로 지정된 멤버함수만 호출할 수 있다
2. 객체를 const로 지정하려면 객체 정의시 클래스 명 앞에 const를 추가한다
3. const Dog happy;
____const 객체 happy
____happy의 초기화된 데이터를 변경할 수 없다.

#include <iostream>
class Dog {
	int age;
public:
	Dog(int a) { age = a; }
	int getAge() const;
	void setAge(int a) { age = a; }
	void view() const
	{
		std::cout << "나는 view\n";
	}
};
int Dog::getAge() const
{
	view();
	return (age);
}
int main()
{
	const Dog happy(5); 			//const 객체
	std::cout << happy.getAge();
	return 0;
}
profile
개발 초보 대학생

0개의 댓글