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/]