C++禁止隐式转换之explicit用法

1.隐式类型转换

#include 
using namespace std;
class Test
{
 public:  
    Test(int num){
     cout << __FUNCTION__ << "(), num = " << num << endl;
  }
}

int main(){
 //编译器自动将整型“隐式转换”为Test类对象
 Test obj = 10;

/*
等同于:
 Test t1(10);
 Test t2 = t1;
*/
 return 0;
}

2.禁止隐式转换关键字:explicit

#include 
using namespace std;
class Test{
public://explicit(显式)构造函数
  //explicit Test(int n){
    cout << __FUNCTION__ << "(), n = " << n << endl;
  }
};

int main(){
  //Test t1 = 222;//编译错误,不能隐式调用其构造函数
  Test t2(12);//显式调用成功
  return 0;
}

 

你可能感兴趣的:(C++学习)