构造函数初始化列表

C++之构造函数初始化列表

C++中面向对象的部分不可避免的会涉及到成员值的初始化,我们一般会采用在构造函数中给成员赋值的方式来完成初始化的工作。如下:

#include <iostream>

using namespace std;

class sth
{
public:
    char* name;
    sth()
    {
        name = "ganlan";
    }
};

int main()
{
    sth s;
    cout << s.name << endl;

    return 0;
}

而其实,这种方式在执行过程中其实是有一定的损耗的,可以这样解释,第八行,在实例化的时候已经调用了默认的构造函数,所以会申请一个空间存储name,而在复写的构造函数中也需要申请一个空间存储“ganlan”,然后再赋值给name,造成空间性能的损耗。可以使用以下的案例来说明这种机制。

#include <iostream>

using namespace std;

class example
{
public:

    example()
    {
        cout << "created it" << endl;
    }
    example(int x)
    {
        cout << "create it with " << x <<endl;
    }
};

class sth
{
    char* name;
    example myExample;
public:

    sth()
    {
        name = "ganlan";
        example myExample(1);
        cout << name << endl;
    }
};

int main()
{
    sth s;

    return 0;
}

以上代码执行结果为:

create it
create it with 1
ganlan

而使用构造函数初始化列表的方法就可以避免这种情况。

#include <iostream>

using namespace std;

class example
{
public:

    example()
    {
        cout << "created it" << endl;
    }
    example(int x)
    {
        cout << "create it with " << x <<endl;
    }
};

class sth
{
    char* name;
    example myExample;
public:

    sth()
        :name("ganlan"), myExample(1)  // 构造函数初始化列表
    {
        cout << name << endl;
    }

};

int main()
{
    sth s;

    return 0;
}

注意:myExample(1) 是一种简写方式,原本需要写为myExample(example(1))

以上代码的运行结果为:

create it with 1
ganlan
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值