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
반응형
'Program Language > C & C++' 카테고리의 다른 글
[C++] noexcept (10) | 2021.10.01 |
---|---|
[C++] atomic (6) | 2021.10.01 |
[C++] thread에서 return 값 받기 (promise/future) (2) | 2021.09.30 |
[C++] 명시적 링크 (Explcit Linking) 시 GetProcAddress NULL 반환 (0) | 2021.07.29 |
[C++] std::string ↔ std::wstring (0) | 2021.06.09 |