2010-07-18 3 views
5

가능한 중복 :과 함께 또는없이 차이가 무엇
What does the explicit keyword in C++ mean?C++의 명시 적 키워드는 무엇입니까?

explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { 
    assign(filename); 
} 

?

+1

가능한 중복 : http://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-mean 당신이 명시 적으로 구조해야 할 것 명시 적 수단 추가 –

답변

4

이것은 생성자를 장식하는 데 사용됩니다. 그렇게 장식 된 생성자는 암시 적 변환을 위해 컴파일러에서 사용할 수 없습니다.

class circle { 
    circle(const int r) ; 
} 

    circle c = 3 ; // implicit conversion using ctor 

컴파일러 여기 원의 ctor 호출 :

C++은에서는 예 "클래스 생성자를 통해"하나의 사용자 제공 변환 "사용자가 제공하는"수단까지 허용 c 원을 구성하고 r에 대해 값 3을 지정합니다.

explicit은 원하지 않을 때 사용됩니다.

class circle { 
    explicit circle(const int r) ; 
} 

    // circle c = 3 ; implicit conversion not available now 
    circle c(3); // explicit and allowed 
5

explicit 키워드는 암시 적 변환을 방지합니다. explicit 키워드없이

// Does not compile - an implicit conversion from const char* to CImg 
CImg image = "C:/file.jpg"; // (1) 
// Does compile 
CImg image("C:/file.jpg"); // (2) 

void PrintImage(const CImg& img) { }; 

PrintImage("C:/file.jpg"); // Does not compile (3) 
PrintImage(CImg("C:/file.jpg")); // Does compile (4) 

, 문 (1) 컴파일러 (A const char*를 받아들이는 생성자를 통해)를 const char*가 암시 적으로 CImg로 변환 할 수 있음을 알 수 있기 때문에 (3) 컴파일 것입니다. 때로는이 암시 적 변환이 항상 바람직하지 않기 때문에 바람직하지 않습니다.

관련 문제