::public/C++
explicit
해맑은욱
2023. 7. 6. 10:41
자신이 원하지 않은 형변환이 일어나지 않도록 제한하는 키워드
class A
{
public:
int num = 1;
public:
// 1. non explicit
A(int n) : num(n) {};
// 2. explicit
explicit A(int n) : num(n) {};
void printA(A a)
{
cout << a.num << endl;
}
};
int main()
{
int i = 11;
// 1번의 경우 컴파일러가 인자를 A 형태로 자동으로 바꿈.
printA(i); // compile ok.
// 2번의 경우 사용자가 원치 않은 형변환이 일어나는 걸 막을수 있음.
printA(i); // compile error.
printA(A(i)); // compile ok. 형변환을 해줘야 함.
}