C++中的explicit关键字(转)

原创作品,转载请标明http://blog.csdn.NET/xiejingfa/article/details/48369081


问题

我们知道,C++在内置类型之间存在隐式类型转换。而在类类型中,也存在这样一种类型转换:当一个类的构造函数只有参数时,会将该类型的一个值隐式转换为对应的类类型。比如下面一个例子:

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Example  
  5. {  
  6. public:  
  7.     int e;  
  8.     Example(int n)  
  9.     {  
  10.         e = n;  
  11.     }  
  12. };  
  13.   
  14. int main()  
  15. {  
  16.     Example example1(100);  // 调用了默认构造函数  
  17.     Example example2 = 200; // 进行了隐式初始化  
  18.     cout << example1.e << endl; // 输出100  
  19.     cout << example2.e << endl; // 输出200  
  20. }  
#include <iostream> 
using namespace std;

class Example
{
public:
int e;
Example(int n)
{
e = n;
}
};

int main()
{
Example example1(100); // 调用了默认构造函数
Example example2 = 200; // 进行了隐式初始化
cout << example1.e << endl; // 输出100
cout << example2.e << endl; // 输出200
}隐式类型转换往往容易发生错误,为了禁止上述的隐式类型转换可以使用explicit关键字。

explicit关键字

explicit关键字用来修饰类的构造函数,被该关键字修饰的类,不能发生上述的隐式类型转换,只能以显形的方式进行类型转换。

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Example  
  5. {  
  6. public:  
  7.     int e;  
  8.     explicit Example(int n)  
  9.     {  
  10.         e = n;  
  11.     }  
  12. };  
  13.   
  14. int main()  
  15. {  
  16.       
  17.     Example example1 = 100; // Error 不存在从”int”到”Example”的适当构造函数  
  18.     Example example2 = static_cast<Example>(200); // 显示转换  
  19.     cout << example2.e;    // 输出200  
  20. }  
#include <iostream> 
using namespace std;

class Example
{
public:
int e;
explicit Example(int n)
{
e = n;
}
};

int main()
{

Example example1 = 100; // Error 不存在从"int"到"Example"的适当构造函数
Example example2 = static_cast&lt;Example&gt;(200); // 显示转换
cout &lt;&lt; example2.e;    // 输出200

}

总结

1、explicit关键可以屏蔽编译器缺省的隐式类型转换;

2、explicit关键字只能用于类内部的构造函数声明,而不能于在类外部的函数声明;

3、explicit只有在构造器只传一个参数的情况下有意义,当构造函数的参数超过两个时会自动取消隐式类型转换。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值