C++ 為類(Class)提供了許多默認(rèn)函數(shù)。如果自己沒有申明,編譯器會為我們提供一個copy構(gòu)造函數(shù)、一個copy assignment操作符和一個析構(gòu)函數(shù)。此外,如果沒有申明任何構(gòu)造函數(shù),編譯器會為我們申明一個default構(gòu)造函數(shù)。很像下面的Empty類:
class Empty{ public: Empty(); Empty(const Empty &rhs); ~Empty(); Empty& operator=(const Empty &rhs);};就像Effective C++說的,如果不想使用編譯器自動生成的函數(shù),就應(yīng)該明確拒絕。
1.C++中的隱式構(gòu)造函數(shù)
如果c++類的其中一個構(gòu)造函數(shù)有一個參數(shù),那么在編譯的時候就會有一個缺省的轉(zhuǎn)換操作:將該構(gòu)造函數(shù)對應(yīng)數(shù)據(jù)類型的數(shù)據(jù)轉(zhuǎn)換為該類對象。
2.Explicit Constructors顯式構(gòu)造函數(shù)
為了避免上面提到的只有一個參數(shù)的構(gòu)造函數(shù)采用的缺省轉(zhuǎn)換操作,在構(gòu)造函數(shù)前,使用Explicit 關(guān)鍵字修飾即可。
3.如下面的例子:
#include <iostream>using namespace std;class B{ public: int data; B(int _data):data(_data){} //explicit B(int _data):data(_data){}};int main(){ B temp=5; cout<<temp.data<<endl; return 0;}程序第11行,將int轉(zhuǎn)換為B類型的對象,就是使用了隱式構(gòu)造函數(shù)。因為B中存在一個只有一個參數(shù)的構(gòu)造函數(shù),且參數(shù)類型也是int。
如果在構(gòu)造函數(shù)前加explicit ,表示為顯示構(gòu)造函數(shù),則第11行編譯不能通過。因為這時,就沒有隱式構(gòu)造函數(shù)啦。
以上這篇淺談C++ Explicit Constructors(顯式構(gòu)造函數(shù))就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答