假使我们界说了Str类如下布局
class Str
{
public:
Str(int n)
Str(const char* p)
.....
}
可以利用如下方法来构建一个工具
Str c(12); Str d=Str(20); Str *z=new Str(21); Str a=10;//此处构建10个巨细的空间 Str b="abcd";//此处构建特定字符串巨细空间 Str f='f'; //与设计不相符的构建方法,这里会构建(int)'f'巨细的内存空间
也许挪用者是但愿Str存’f’这一个字符,尽量Str没有提供这样的接口,可是编译的时候并不会报错,因为这里存在隐式转换,将char型转换为 Int型,这样就与挪用者的初志不切合了。而利用explicit可以杜绝这种隐式转换,在编译的时候就不会让其通过。可见explicit对付写一些基本库供他人挪用还长短常有须要的.
代码:
#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:"<<strarr<<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;
}
出处[http://creator.cnblogs.com/]
