c ++中初始化程序和默认初始化程序列表之间的差异 [英] Difference between initializer and default initializer list in c++

查看:104
本文介绍了c ++中初始化程序和默认初始化程序列表之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,
我有一个问题,但找不到很长时间的答案,也就是
下面的2个语句有关参数
初始化有什么区别?

I have a question but cannot find the answer for a long time, that is, what's difference between the following 2 statements about the parameter initialization?

class A::A() 
    : a(0), b(0), c(0) 
{ 
}

class A::A() 
{ 
    a = 0 
    b = 0; 
    c = 0; 
} 



我知道有直接初始化和复制初始化
不知道什么是其他差异,如果有任何描述
关于第一个语句?

I know there is "direct initialization" and "copy initialization", but I don't know what's the other differences and if there is any description about the first statement?

提前感谢

推荐答案

默认初始化列表的目的是在类中初始化常量变量。
因为常量变量在对象初始化之前被初始化。

The purpose of default initialization list is to initialize the constant variable with in the class. Because the constant variable is initialized before the object is initialized.

我提供一个示例来解释这两个初始化之间的区别:

I provide one sample to explain the difference between these two initializations:

 class A
   {
       private:
          const int x;

  };

  A::A():x(5)        //this code works fine
  {

    }

    A::A()       //this code is wrong.const variable is not initialized once object         
   {
    x=5;
    }

这篇关于c ++中初始化程序和默认初始化程序列表之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆