一、基本格式
C++提供了初始化列表语法,用来初始化属性。
基本格式:
构造函数(参数1,参数2,参数3...):属性1(值1),属性2(值2)... { // 构造函数体 }
例子
#include <iostream> using namespace std; class Person{ public : // 初始化列表初始化属性 Person():m_a(10),m_b(20),m_c(30){ } // 初始化列表初始化属性 Person(int a,int b,int c):m_a(a),m_b(b),m_c(c){ } void Print_Info(){ cout << ">>>>>>>>>>>>>>>>>" << endl; cout << "m_a:" << m_a << endl; cout << "m_b:" << m_b << endl; cout << "m_c:" << m_c << endl; cout << "<<<<<<<<<<<<<<<<<" << endl << endl; } private: int m_a; int m_b; int m_c; }; int main(){ (Person()).Print_Info(); (Person(1,2,3)).Print_Info(); }
初始化列表只能初始化一次,初始化列表中的元素不能重复。
编译器允许构造函数赋初值和初始化列表初始化混用。
Person(int a,int b,int c):m_a(a),m_b(b),m_c(c){ m_a = 20; } // 最终结果: m_a 为20
初始化列表的执行是先于构造函数的。
二、使用场景
const成员变量
、引用成员变量
、没有默认构造函数的类成员
只能在初始化列表初始化。
- const成员变量必须在定义的时候初始化
- 引用成员变量必须在定义的时候初始化
- 没有默认构造函数的类类型成员变量
#include <iostream> using namespace std; class Cat { public: string name; // 默认构造函数是不用传参就可以调用的构造函数,有三种 // 1. 无参默认构造函数 // 2. 所有参数带默认值的构造函数 // 3. 编译器自动生成的默认构造函数 Cat( string name) : name(name){ // 自定义了构造函数后, 编译器就不会生成默认构造函数 // 因此Cat类没有默认构造函数 } }; class SmallCat{ public: SmallCat(string name,int weight,int& age):weight(weight),cat(Cat(name)),age(age) { } void Print_Info(){ cout << cat.name << endl; cout << weight << endl; cout << age << endl; } private: const int weight; Cat cat; int & age; }; int main(){ int age = 2; (SmallCat("yyrwkk",1,age)).Print_Info(); }
尽量使用初始化列表初始化,初始化列表的执行是在构造函数的用户代码之前。
对于自定义类型成员变量,会先使用初始化列表初始化。
成员变量初始化的顺序是成员变量在类中的声明次序
,与初始化列表中的先后次序无关
。