在Qt的開發中看到explicit,由此展開搜索。
隱式:編譯器完成的轉換,如
int a = 1; float b = 3; float sum; sum = a + b; //a本是int,編譯器將a隱式地轉化為了float
顯式:用戶完成的轉換,如
float a=1; float b=3; int s; s = (int)a+(int)b;//a與b被顯式地轉化為了float
對於函數而非數據,這里有另一個例子[引用]:
#include <iostream> using namespace std;
class A{ int x; public: A(){x=0;cout<<"Create A:0"<<endl;} A(int a){x=a;cout<<"Create A:"<<x<<endl;} ~A(){cout<<"Delete A:"<<x<<endl;} }; void main() { A a1; A *a2=new A(10); delete a2; }
這個程序中:
A a1; 隱式調用了A()
A *a2=new A(10);顯式調用了A(int a) 重載后的A() delete a2;以及程序結束時都隱式調用了析構函數~A()
關於explicit關鍵字,在網上找了一下,大多很繁瑣。
這篇博客講的比較深入淺出。推薦:http://www.cnblogs.com/cutepig/archive/2009/01/14/1375917.html
一句話:explicit用於構造函數,抑制隱式轉換的發生,防止出現誤區。
引用:C++ 隱式和顯式的區別 - https://zhidao.baidu.com/question/116242760.html