C++學(xué)習(xí)筆記 09 構(gòu)造函數(shù)初始化成員變量

注意事項(xiàng)

  1. 盡量用括號(hào)的形式去初始化成員變量,避免成員變量的被多次初始化
  2. 括號(hào)形式構(gòu)造成員變量: 順序需和成員變量定義順序保持一致
#include<iostream>

class Entity {
public:
    int m_Score;
    std::string m_Name;

    //以屬性名稱 + 括號(hào) 的形式在構(gòu)造函數(shù)中為屬性賦值
    Entity() :
        //這個(gè)順序需要和上面屬性的順序保持一致
        m_Score(0), m_Name("Unknown") {
    }

    Entity(const std::string& name) {
        m_Name = name;
    }
};

void testOrderConstruct() {
    Entity e0;
    std::cout << e0.m_Name << " | " << e0.m_Score << std::endl;

    Entity e1("Cherno");
    std::cout << e1.m_Name << " | " << e1.m_Score << std::endl;
}


class Example {
public:
    Example() {
        std::cout << "Create Example." << std::endl;
    }
    Example(int x) {
        std::cout << "Create Example with " << x << std::endl;
    }
};

class Entity2 {
public:
    std::string m_Name;
    //這里會(huì)調(diào)用其默認(rèn)構(gòu)造函數(shù)
    Example example;

    //以屬性名稱 + 括號(hào) 的形式在構(gòu)造函數(shù)中為屬性賦值
    Entity2() :
        //這個(gè)順序需要和上面屬性的順序保持一致
        m_Name("Unknown"), 
        //保障只會(huì)調(diào)用此構(gòu)造函數(shù),上面的屬性不會(huì)調(diào)用Example的空構(gòu)造函數(shù)
        //example(Example(8)) {
        //簡(jiǎn)寫(xiě),不會(huì)再去調(diào)用Example的空構(gòu)造方法
        example(8)
    {
        //在構(gòu)造函數(shù)體中這種寫(xiě)法會(huì)調(diào)用2次,1次帶數(shù)字的構(gòu)造函數(shù),一次空構(gòu)造函數(shù)
        //example = Example(8);
    }

    Entity2(const std::string & name): m_Name(name)
    {

    }
};


void testEntity2() {
    //調(diào)用了Example的構(gòu)造函數(shù)兩次
    Entity2 e0;
}

int main() {
    //testOrderConstruct();
    testEntity2();
    std::cin.get();
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容