Program Language/C & C++

[C++] explicit 키워드

야곰야곰+책벌레 2021. 10. 1. 09:27
728x90
반응형

explicit 키워드는 자신이 원하지 않는 형 변환이 일어나지 않게 해 준다.

형 변환을 컴파일러가 자동으로 해주는 것을 막으며, 컴파일 시 error를 발생시킨다.

 

<형 변환의 예>

#include <iostream>

class A
{
public:
	A(int n) : num(n) {};
	int num;
};

void printA(A a)
{
	std::cout << a.num << std::endl;
}

int main()
{
	int n = 10;
	printA(n);

	return 0;
}

에러 없이 결과를 확인할 수 있다.

하지만 explicit 키워드를 붙이면 컴파일 에러가 난다.

확인해 보자.

#include <iostream>

class A
{
public:
	explicit A(int n) : num(n) {};
	int num;
};

void printA(A a)
{
	std::cout << a.num << std::endl;
}

int main()
{
	int n = 10;
	printA(n);

	return 0;
}

explicit이 선언되어 있어서 convert를 할 수 없다는 에러를 발생시킨다.

728x90
반응형