explicit 显示的类型转换运算符

时间:2023-03-09 19:17:00
explicit 显示的类型转换运算符

C++提供了关键字explicit,可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生。声明为explicit的构造函数不能在隐式转换中使用。

调用构造函数可以分为显示调用和隐式调用,当用赋值初始化就是显示调用,赋值初始化是隐式调用

比如:

 class Test1
{
public:
Test1(int n)
{
num=n;
}//普通构造函数
private:
int num;
};
class Test2
{
public:
explicit Test2(int n)
{
num=n;
}//explicit(显式)构造函数
private:
int num;
};
int main()
{
Test1 t1=;//隐式调用其构造函数,成功
Test2 t2=;//编译错误,不能隐式调用其构造函数
Test2 t2();//显式调用成功
return ;
}