Date
May. 19th, 2024
 
2024年 4月 12日

Post: C++ Primer 011 : 初始化列表

C++ Primer 011 : 初始化列表

Published 12:05 May 25, 2013.

Created by @ezra. Categorized in #Programming, and tagged as #C/C++.

Source format: Markdown

Table of Content

本篇主要介绍C++ 中的初始化列表。

class 类名 {
    类名(行参1,行参2):成员变量1(行参1),成员变量2(行参2) {
        //成员变量1 = 行参1;
        //成员变量2 = 行参2;
        //...
    }
};
  • 成员变量的初始化顺序和初始化列表中的顺序无关,而是取决于成员变量的声明顺序。

来看一个例子,找出下面代码的不妥之处:

class Dumy {
private:
    int m_len;
    string m_str;
public:
    Dumy(string str):m_str(str),m_len(m_str.length()){}
};

根据上面代码,实际上先给 m_len 进行赋值,然后给 m_str 赋值,但在给 m_len 赋值时 m_str 为空,所以造成 m_len 值错误。

修改:

//>1
class Dumy {
private:
    string m_str;
    int m_len;
public:
    Dumy(string str):m_str(str),m_len(m_str.length()){}
};
//>2
class Dumy {
private:
    int m_len;
    string m_str;
public:
    Dumy(string str):m_str(str),m_len(str.length()){}
};
  • 类中的成员变量叫声明,在类创建对象的时候才会定义成员变量。

初始化列表的必要性

  • 类中包含常量和引用型的成员变量时,必须通过构造函数的初始化列表显式的对其进行初始化。

  • 在子类中显式的构造其基类部分的时候需要使用初始化列表的方式。

/*
    初始化列表的必要性initialize.cpp
*/
#include <iostream>

using namespace std;

class User {
private:
    const int m_id;
    int &m_age;
public:
    User(int id,int age):m_id(id),m_age(age) {
        //这里初始化失败,因为在此之前已经被初始化
        //m_id = id;
        //m_age = age;
    }
    void show(void) {
        cout << '(' << m_id << ',' << m_age << ')' << endl;
    }
};

int main(void) {
    User uesr(101,20);
    return 0;
}
Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF