构造函数初始化列表

对于一个类,我们需要给他赋初值,这时候构造函数就起到了这个作用,构造函数在类实体被建立的那一刻起就被调用并且给类赋上了初值,下面为类写两个构造函数

#include<iostream>
#include<string>

class Entity
{
private:
    std::string m_Name;
public:
    Entity()
    {
        m_Name = "Unknow";
    }
    Entity(const std::string& name)
    {
        m_Name = name;
    }
    const std::string &GetName()const
    {
        return m_Name;
    }
};

int main()
{
    Entity e0;
    std::cout << e0.GetName() << std::endl;

    Entity e1("Wangtn");//因为传入的数据时常量字符串,所以构造函数的输入也应该是const类型
    std::cout << e1.GetName() << std::endl;

    std::cin.get();
}

可以看到打印结果

 

 

 另外一种初始化方法是通过构造函数初始化链表来完成

#include<iostream>
#include<string>

class Entity
{
private:
    std::string m_Name;
public:
    Entity()
        :m_Name("Unknow")
    {
    }
    Entity(const std::string& name)
        :m_Name(name)
    {
    }
    const std::string &GetName()const
    {
        return m_Name;
    }
};

int main()
{
    Entity e0;
    std::cout << e0.GetName() << std::endl;

    Entity e1("Wangtn");//因为传入的数据时常量字符串,所以构造函数的输入也应该是const类型
    std::cout << e1.GetName() << std::endl;

    std::cin.get();
}

注意构造函数初始化链表的格式,而且当类中有多个成员变量时,使用构造函数初始化链表进行初始化时要按照变量的顺序来,而且如果有多个构造函数,所有的构造函数初始化变量的顺序必须相同。

#include<iostream>
#include<string>

class Example
{
public:
    Example()
    {
        std::cout << "Create Entity" << std::endl;
    }
    Example(int x)
    {
        std::cout << "Create Entity with" << x <<"!"<< std::endl;
    }
};
class Entity
{
private:
    std::string m_Name;
    int x, y, z;
    Example m_Example;//1
public:
    Entity()
    {
        m_Name = "Unknow";
        m_Example = Example(8);//2
    }
    Entity(const std::string& name)
    {
        m_Name = name;
    }
    const std::string &GetName()const
    {
        return m_Name;
    }
};

int main()
{
    Entity e0;


    std::cin.get();
}

 

 

上面代码可以看到,我只新建了一个实体类Entity e0,但是却是用了两次Example的构造函数,也就是说Example这个类被创建了两次,第一次和第二次创建如程序注释所标注,如果使用构造函数初始化链表

#include<iostream>
#include<string>

class Example
{
public:
    Example()
    {
        std::cout << "Create Entity" << std::endl;
    }
    Example(int x)
    {
        std::cout << "Create Entity with" << x <<"!"<< std::endl;
    }
};
class Entity
{
private:
    std::string m_Name;
    int x, y, z;
    Example m_Example;
public:
    Entity()
        :m_Example(Example(8))//:m_Example(8)
    {
        m_Name = "Unknow";
    }
    Entity(const std::string& name)
    {
        m_Name = name;
    }
    const std::string &GetName()const
    {
        return m_Name;
    }
};

int main()
{
    Entity e0;


    std::cin.get();
}

 

 

可以看到Example只建立了一次,注释后的写法结果是一样的。所以结论就是没有理由不使用构造函数初始化链表,他可以简化代码,节约资源,并且不会出错

posted @ 2020-04-21 17:24  Wangtn  阅读(449)  评论(0编辑  收藏  举报