c++对象模型学习篇(一)(default construct)

    由于看了《Inside C++对象模型》这本书,顺手把学到的东西记下来,这样跟深刻一些。

   我们来看看default constructor这节,在课本上,我们都学到了,如果在一个class 中没有defaulst constructor,在class object 中compiler将会给我们自动生成一个defalut constructor。这个说法不太严谨。是不是当我们需要时,compiler就会给我们合成呢。答案是否定的。能否合成一个default constructor,要看是谁需要这个default constructor,compiler or us?

   For example:

      class people

      {

          public:

              int age;

               .......

      }

void  Fun ()

{

   people it;

    if(it.age>...)

    {

      ...

    }

  ...

}

看看这个例子,当我们需要这个age member时,compiler是否会给我们初始化这个值呢?No,this is just what we need.

compiler会视而不见,不会管我们的闲事,因此也就不会为我们合成default constructor。

   下面我们就看看一看,什么时候compiler会给我们合成default constructor.

    1.带有class members 中有 带有default constructor的member  object。

 但是这个default constructor 只会在constuctor被调用的的时候合成,而且合成的default constructor只满足compiler需要。

我们再看个例子

class people

      {

       public:

 

        people();

 

          public:

              int age;

               .......

      }

    class company

     {

          public:

               String name;

               people employer;

  ...

 

     }

   void fun()

  {

      company cp; //这个时候才合成default constructor

      if(cp.name.....)

         . ..

 

     ...

  }

此时compiler是不会给我们初始化这个值的,compiler所执行的代码可参考为:

inline company:: company()

{

    employer.people::people();

 

}

因此我们需要一个explicit default constructor,但是这样,compiler就不会合成一个default constructor,但是它将上面的代码insert into  your default constructor.

   寝室快停电了,还有点事,先保存再说,下面还有3点没说,待下篇吧。

      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值