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/

  • 相关阅读:
    linux 免交互状态下修改用户密码
    Sqlmap基础(一)
    cmd命令行指定系统延迟关机时间
    Shell 是个什么玩意
    Linux Shell脚本入门:tee命令
    shell脚本 -d 是目录文件,那么-e,-f等说明
    修改linux终端命令行颜色
    Linux 动画显示
    OpenVAS漏洞扫描基础教程之OpenVAS概述及安装及配置OpenVAS服务
    Curl命令使用
  • 原文地址:https://www.cnblogs.com/wuzhenwei/p/4566469.html
Copyright © 2011-2022 走看看