[c++] 初始化列表

  • c++进行类成员的初始化时,可在构造函数体中对成员赋值,也可采用初始化列表 
  • 成员变量比较多时,采用初始化列表更方便
  • 可用于全部或部分变量
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Student{
 5 private:
 6     char *m_name;
 7     int m_age;
 8     float m_score;
 9 public:
10     Student(char *name, int age, float score);
11     void show();
12 };
13 
14 //采用初始化列表
15 Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){
16     //TODO:
17 }
18 void Student::show(){
19     cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
20 }
21 
22 int main(){
23     Student stu("小明", 15, 92.5f);
24     stu.show();
25     Student *pstu = new Student("李华", 16, 96);
26     pstu -> show();
27 
28     return 0;
29 }

参考:

c++初始化列表:

http://c.biancheng.net/view/2223.html

Qt初始化列表:

https://www.jianshu.com/p/30b68fe7487f

原文地址:https://www.cnblogs.com/cxc1357/p/11894578.html