C + + 11 class member initialization

Source: Internet
Author: User

以前不能在类定义中初始化成员? 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.