explicit的使用

#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);进行约束;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值