#include <iostream>
using namespace std;
//explicit为的是处理只有一个参数的构造函数,让其构造过程只能使用显示的调用
//如果没有使用explicit时我们可以使用只含有一个参数构造函数的一个特殊的使用方法
class CExplicitTest
{
public:
/*explicit*/ CExplicitTest(int iInput);
/*explicit*/ CExplicitTest(const char* strInput);
private:
char m_strInput[256];
int m_iInput;
};
CExplicitTest::CExplicitTest(int iInput)
{
memset(m_strInput, 0, 256);
m_iInput = iInput;
cout<<"CExplicitTest(int iInput)"<<iInput<<endl;
}
CExplicitTest::CExplicitTest(const char* strInput)
{
m_iInput = 0;
memcpy(m_strInput, strInput, 256);
cout<<"CExplicitTest(CString strInput)"<<strInput<<endl;
}
int main()
{
//正常用法
CExplicitTest explicitTest(1);
//这是只有一个参数的特殊用法(很好很强大)==>这就是隐式使用
CExplicitTest explicitTest1 = 10;
//不错原来一个参数的用法这么好(还是很强大)==>这就是隐式使用
CExplicitTest explicitTest2 = "abcd";
//以上的使用似乎会引起不好的返应
//还是对其进行约束一下那就只能使用explicit修饰一下构造函数吧
return 0;
}
以上看不出explicit的实用,如下你会发现explicit的应用
#include <iostream>
using namespace std;
class String
{
private:
int m_size;
char *p;
public:
String(int sz);
String(const char*s);
~String();
};
String::String(int sz)
{
p = new char[sz];
cout<<"给我String开辟"<<sz<<"个空间"<<endl;
}
String::String(const char* s)
{
int len = strlen(s);
p = new char[strlen(s)+1];
strcpy(p, s);
cout<<p<<endl;
}
String::~String()
{
if(NULL != p)
{
delete[] p;
p = NULL;
}
}
int main()
{
//给string 开辟10个空间
String s(10);
//我想给String赋上一个字符串,结果不小心打成了100
String b = 100;//郁闷,这不是我要的结果,出错了
//我要的是如下的内容
//String c = "100";
return 0;
}
以上运行没有错误,可是逻辑上出现了错误,我们不应该用String b = 100,我们是要使用String c = "100";
所以在这里可以使用explicit对 String(int sz);进行约束;