zoukankan      html  css  js  c++  java
  • C++类构造函数中的成员初始化

    成员初始化列表,形式如下(在参数列表后面以冒号为起点,之后是一个初始化列表):

    Rectangle::Rectangle (int x, int y) : width(x), height(y) { }
    

     

    关于构造函数、以及成员初始化列表的细节,见[1]。

    这里摘出比较关键的两段话:

    For members of fundamental types, it makes no difference which of the ways above the constructor is defined, because they are not initialized by default, but for member objects (those whose type is a class), if they are not initialized after the colon, they are default-constructed.
    对于基本类型(int, float, bool)等,用不用成员初始化列表没有差异;而对于对象(基于类, class),如果没有进初始化列表,在执行构造函数函数体前,会对其进行缺省构造。

    Default-constructing all members of a class may or may always not be convenient: in some cases, this is a waste (when the member is then reinitialized otherwise in the constructor), but in some other cases, default-construction is not even possible (when the class does not have a default constructor). In these cases, members shall be initialized in the member initialization list. 

    在相当一部分情况下,进行缺省构造是不合理的行为。这也正是成员初始化列表存在的意义所在。

    参考:

    [1]http://www.cplusplus.com/doc/tutorial/classes/

  • 相关阅读:
    Unicode详解
    VC++ 6.0 中如何使用 CRT 调试功能来检测内存泄漏
    关于MFC下检查和消除内存泄露的技巧
    ASCII 、GB2312、GBK、GB18030、unicode、UTF8字符集编码详解
    A note from UrlEscape Function
    Unicode和UTF8之间的转换详解
    Base64编码
    全面解读WM_NOTIFY
    关于URL编码
    URL的#号
  • 原文地址:https://www.cnblogs.com/wuzhenwei/p/4566469.html
Copyright © 2011-2022 走看看