#include<iostream>classSomething{private:intm_value1{};doublem_value2{};charm_value3{};public:Something():m_value1{1},m_value2{2.2},m_value3{'c'}// Initialize our member variables{// No need for assignment here}voidprint(){std::cout<<"Something("<<m_value1<<", "<<m_value2<<", "<<m_value3<<")\n";}};intmain(){Somethingsomething{};something.print();return0;}
#include<iostream>classSomething{private:constintm_value;public:Something(intx):m_value{x}// directly initialize our const member variable{}voidprint(){std::cout<<"Something("<<m_value<<")\n";}};intmain(){std::cout<<"Enter an integer: ";intx{};std::cin>>x;Somethings{x};s.print();return0;}
程序的输出结果:
12
Enter an integer: 4
Something(4)
法则
Const 成员变量必须被初始化。
使用成员初始化列表初始化数组类型成员
下面例子中的类包含一个数组类型的成员:
123456
classSomething{private:constintm_array[5];};
在 C++11 之前,你只能通过成员初始化列表,对数组成员进行0初始化:
1 2 3 4 5 6 7 8 91011
classSomething{private:constintm_array[5];public:Something():m_array{}// zero initialize the member array{}};
classSomething{private:constintm_array[5];public:Something():m_array{1,2,3,4,5}// use uniform initialization to initialize our member array{}};
初始化类类型的成员变量
成员初始化列表也可用于类类型成员变量的初始化:
1 2 3 4 5 6 7 8 910111213141516171819202122232425
#include<iostream>classA{public:A(intx=0){std::cout<<"A "<<x<<'\n';}};classB{private:Am_a{};public:B(inty):m_a{y-1}// call A(int) constructor to initialize member m_a{std::cout<<"B "<<y<<'\n';}};intmain(){Bb{5};return0;}
classSomething{private:intm_value1{};doublem_value2{};charm_value3{};public:Something():m_value1{1},m_value2{2.2},m_value3{'c'}// everything on one line{}};
classSomething{private:intm_value1{};doublem_value2{};charm_value3{};floatm_value4{};public:Something(intvalue1,doublevalue2,charvalue3='c',floatvalue4=34.6f)// this line already has a lot of stuff on it:m_value1{value1}// one per line,m_value2{value2},m_value3{value3},m_value4{value4}{}};