Itme4 对象使用前进行初始化

fun(){
int a;
printf("%d\n", a);
cout << a << endl;
//会报错 使用了未初始化的变量a
}
//若a是全局变量则不会报错 会默认初始化为0

 在对象中优先使用初始化列表:

ABEntry::ABEntry(const std::string& name, const std::string& address,
                 const std::list<PhoneNumber>& phones)

{

  theName = name;                       // these are all assignments,

  theAddress = address;                 // not initializations

  thePhones = phones;

  numTimesConsulted = 0;

}

这样是没有使用初始化列表 在调构造函数之前会对这个对象的成员进行默认的初始化,再到构造函数当中 去进行赋值,  所以这里是进行的赋值操作并不是初始化。

ABEntry::ABEntry(const std::string& name, const std::string& address,
                 const std::list<PhoneNumber>& phones)

: theName(name),
  theAddress(address),                  // these are now all initializations
  thePhones(phones),
  numTimesConsulted(0)

{}                                      // the ctor body is now empty

这是初始化列表 

局部静态对象的的初始化顺序

在不同的文件中 在一个文件中使用另一个文件的局部静态变量  可能会未进行初始化

这可能是由于文件的位置不同

class FileSystem { ... };           // as before

FileSystem& tfs()                   // this replaces the tfs object; it could be
{                                   // static in the FileSystem class
  static FileSystem fs;             // define and initialize a local static object
  return fs;                        // return a reference to it
}

class Directory { ... };            // as before

Directory::Directory( params )      // as before, except references to tfs are
{                                   // now to tfs()
  ...
  std::size_t disks = tfs().numDisks();
  ...
}

Directory& tempDir()                // this replaces the tempDir object; it
{                                   // could be static in the Directory class
  static Directory td;              // define/initialize local static object
  return td;                        // return reference to it
}
  • 手动初始化 内建类型的对象,因为 C++ 只在某些时候才会自己初始化它们。

  • 在 构造函数中,用成员初始化列表代替函数体中的 赋值。初始化列表中 数据成员的排列顺序要与它们在类中被声明的顺序相同。

  • 通过用局部静态对象代替 非局部静态对象来避免跨转换单元的 初始化顺序问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值