構(gòu)造函數(shù)的分類
這里簡單地將C++中的構(gòu)造函數(shù)分一下類,直接看下面的代碼表達(dá),說明在注釋中:
#include <iostream> using namespace std; class Text { public: Text() // 無參數(shù)構(gòu)造函數(shù) { m_a = 0; m_b = 0; cout << "無參數(shù)構(gòu)造函數(shù)" << endl; } Text(int a) // 有參數(shù)構(gòu)造函數(shù) { m_a = a; m_b = 0; cout << "無參數(shù)構(gòu)造函數(shù)" << endl; } Text(int a, int b) // 有參數(shù)構(gòu)造函數(shù),有三種調(diào)用方法 { m_a = a; m_b = b; cout << "有參數(shù)構(gòu)造函數(shù)" << endl; } // 賦值構(gòu)造函數(shù),也叫copy構(gòu)造函數(shù) Text(const Text& obj) { cout << "這也是構(gòu)造函數(shù)" << endl; } ~Text(); private: int m_a; int m_b; }; int main() { // 1括號法 Text t1; // 調(diào)用無參數(shù)構(gòu)造函數(shù) // 2等號法 Text t2 = (3, 4, 5, 6, 7); // C++對等號進(jìn)行了加強,c++編譯器自動的調(diào)用構(gòu)造函數(shù) // 3直接調(diào)用構(gòu)造函數(shù),手動調(diào)用構(gòu)造函數(shù) Text t3 = Text(1, 2); // 這里涉及到匿名對象 return 0; } 構(gòu)造函數(shù)調(diào)用規(guī)則研究
1)當(dāng)類中沒有定義任何一個構(gòu)造函數(shù)時,c++編譯器會提供默認(rèn)無參構(gòu)造函數(shù)和默認(rèn)拷貝構(gòu)造函數(shù)
2)當(dāng)類中定義了拷貝構(gòu)造函數(shù)時,c++編譯器不會提供無參數(shù)構(gòu)造函數(shù)
這里一定注意,當(dāng)你只定義一個拷貝構(gòu)造函數(shù),在創(chuàng)建對象時是不能直接調(diào)用無參數(shù)構(gòu)造函數(shù)的。
3) 當(dāng)類中定義了任意的非拷貝構(gòu)造函數(shù)(即:當(dāng)類中提供了有參構(gòu)造函數(shù)或無參構(gòu)造函數(shù)),c++編譯器不會提供默認(rèn)無參構(gòu)造函數(shù)
當(dāng)類中定義了一個多參數(shù)的構(gòu)造函數(shù),那么也是不存在無參數(shù)構(gòu)造函數(shù)
4 )默認(rèn)拷貝構(gòu)造函數(shù)成員變量簡單賦值
總結(jié):只要你寫了構(gòu)造函數(shù),那么你必須用。
也再次印證了拷貝構(gòu)造函數(shù)也是構(gòu)造函數(shù),一定要注意這個易錯點。
新聞熱點
疑難解答