2010-07-18 9 views
5

संभव डुप्लिकेट:
What does the explicit keyword in C++ mean?सी ++ में स्पष्ट कीवर्ड क्या है?

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 कॉल करेगा:

सी ++ में एक उपयोगकर्ता द्वारा प्रदत्त रूपांतरण है, जहां "उपयोगकर्ता द्वारा प्रदान की" का अर्थ है अप करने के लिए अनुमति देता है, "एक वर्ग निर्माता के माध्यम से", जैसे, , buildinmg सर्कल cr के लिए 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 कीवर्ड निहित रूपांतरण रोकता है।

// 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) 
explicit कीवर्ड बिना

, बयान (1) और (3) संकलन क्योंकि संकलक (एक const char* को स्वीकार निर्माता के माध्यम से) देख सकते हैं कि एक const char* परोक्ष एक CImg में बदला जा सकता हैं। कभी-कभी यह निहित रूपांतरण अवांछनीय है क्योंकि यह हमेशा समझ में नहीं आता है।

संबंधित मुद्दे