以前不能在类定义中初始化成员? c++11允许这样做了,其语法类似于下面:
class Session{ int10; double mem2 {1966.54}; short mem3; public: Session(); //#1 Session(short s) : mem3(s) {} //#2 Session(intdoubleshort s) : mem1(n), mem2(d),mem3(s) {} //#3
You can use an equal sign or a curly brace version of initialization, but you cannot initialize with the bracket version. The results are provided with a member initialization list for the first two constructors and the MEM1 and MEM2 are specified
The same value:
Session (): Mem1 (Ten), mem2 (1996.54) {}
Session (Short s): Mem1 (Ten), MEM2 (1996.54), mem3 (s) {}
By using in-class initialization, you avoid writing duplicate code in the constructor, which reduces the programmer's workload, boredom, and error opportunities.
If the constructor provides the corresponding value in the member initialization list, the default values will be overwritten, so the third constructor overrides the initialization of the members in the class.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + 11 class member initialization