在早期的C++中。假設須要一些接受一些參數的構造函數,同一時候須要一個不接收不論什么參數的默認構造函數。就必須顯示地編寫空的默認構造函數.比如:
//tc.h
class A{ private: int i; public: A(){}; A(int ii); };但最好就是接口和聲明分離。那么就是例如以下的定義
//tc,h class A{ private: int i; public: A(); A(int ii)。 };這樣,就必須在實現中給出空參數構造函數的實現:
#include <iostream> #include "tc.h" using namespace std; A::A(){//必須給出事實上現 }; A::A(int ii){ i=ii; } void A::show()const{ std::cout<<"this is A object!"<<std::endl; }; int main() { A a; a.show(); }為了避免手動編寫空默認構造函數,C++11引入了顯示默認構造函數的概念,從而僅僅需在類的定義中編寫空默認構造函數而不須要在實現文件里提供事實上現:
//tc.h #ifndef tc_h_ #define tc_h_ class A{ private: int i; public: A()=default;//default A(int ii); void show()const; }; #endif
//tc.cpp #include <iostream> #include "tc.h" using namespace std; /* A::A(){//不必給出事實上現 }; */ A::A(int ii){ i=ii; } void A::show()const{ std::cout<<"this is A object!"<<std::endl; }; int main() { A a; a.show(); }編譯以及運行結果:
相同的,C++還支持顯式刪除構造函數的概念。
比如。你想定義一個類。這個類沒有不論什么的構造函數,而且你也不想讓編譯器自己主動生成一個默認的空參數的構造函數,那么你就能夠顯式地刪除默認構造函數。
//tc.h #ifndef tc_h_ #define tc_h_ class A{ private: int i; public: A()=delete;//delete void show()const; }; #endif
//tc.cpp #include <iostream> #include "tc.h" using namespace std; /* A::A(){//必須給出事實上現 }; A::A(int ii){ i=ii; }*/ void A::show()const{ std::cout<<"this is A object!"<<std::endl; }; int main() { A a; a.show(); }
編譯結果:
能夠看到,默認構造函數被刪除了。那么。能不能刪除一些其它的帶參數構造函數呢?
事實上這個問題有點多余,由於假設你不想要這個構造函數,你不定義這個帶參的構造函數就OK了!