淺談C++中的構(gòu)造函數(shù)分類及調(diào)用規(guī)則
構(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)行了加強(qiáng),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ù),一定要注意這個易錯點。
相關(guān)文章
C++函數(shù)指針與指針函數(shù)有哪些關(guān)系和區(qū)別
函數(shù)指針是一個指針變量,它可以存儲函數(shù)的地址,然后使用函數(shù)指針,這篇文章主要介紹了C++中函數(shù)指針與指針函數(shù)有哪些關(guān)系和區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值2022-08-08C++?LeetCode0547題解省份數(shù)量圖的連通分量
這篇文章主要為大家介紹了C++?LeetCode0547題解省份數(shù)量圖的連通分量示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12基于C++浮點數(shù)(float、double)類型數(shù)據(jù)比較與轉(zhuǎn)換的詳解
本篇文章是對C++中浮點數(shù)(float、double)類型數(shù)據(jù)比較與轉(zhuǎn)換進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05