C + + Explicit keyword usage scenarios

Source: Internet
Author: User

If we define the STR class as follows structure

Class Str  
{public  
:  
     
str (int n)  
     
str (const char* p) ...  
     
}

You can build an object by using the following methods

Str C (a);  
Str D=str (m);  
STR *z=new STR (n);  
STR a=10;//here constructs 10 size space  
str b= "ABCD";//here constructs a specific string size space  
str f= ' F ';   In a way that does not match the design, the memory space (int) ' F ' will be built here

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

Perhaps the caller is expecting STR to save the ' F ' character, although STR does not provide such an interface, but compiles without an error, because there is an implicit conversion, converting the char to an int, so that it does not conform to the caller's intent. Using explicit eliminates this implicit conversion and does not allow it to be passed at compile time. Visible explicit is necessary to write some base libraries for others to invoke.

Code:

#include <iostream> using namespace std;  
                Class Str {public:/* explicit*/str (int n)//try explicit here {capacity=n;  
        Getmem ();  
                } Str (const char* p) {Capacity=strlen (P) +1;  
                Getmem ();  
        strcpy (STRARR,P);  
        } ~str () {if (strarr!=null) free (Strarr); } void Printfvalue () {cout<< "len:" <<capacity<< "str:" <<s  
        trarr<<endl;  
        } private:void Getmem () {strarr= (char*) malloc (sizeof (char) *capacity);  
        } private:int capacity;  
Char *strarr;  
      
};  
        int main () {STR C (12);  
        Str D=str (20);  
        STR *z=new STR (21);  
        Str a=10;  
        Str b= "ABCD";  
      Str f= ' F ';  C.printfvalue ();  
        D.printfvalue ();  
      
        Z->printfvalue ();  
        A.printfvalue ();  
        B.printfvalue ();  
        F.printfvalue ();  
return 1; }

Origin [http://creator.cnblogs.com/]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.