How a const member or reference member must initialize a list by using a constructor

Source: Internet
Author: User

#include <iostream.h>class  a{    constint  A;     int b;}; void Main () {    A obja;}
The following error occurred in the compilation: Error C2512: ' A ': No appropriate default constructor available;
If you remove the const, you're right!
#include <iostream.h>classa{ Public:    Const intA; intb; A (intx): A (x) {}};voidMain () {A Obja (2); cout<<obja.a<<Endl; cout<<obja.b<<endl;//is not automatically initialized}

There are two ways to initialize a constructor
1 the way in which an assignment statement is used in the body of a constructor.
2 The way the list is initialized with a constructor function.
It is important to note that the execution of the initialization list precedes the execution of the constructor body. Also, some special members, such as constant members and reference members, must be initialized in the initialization list.
This means that once you have a const member or reference member in a class, you cannot use the default constructor. It must be initialized with a user-defined constructor, and it is initialized in the same way that an expression is used.
#include <iostream.h>class  a{  public:    int &A;     int  b;
//a is a reference to B A (): B (9), a (b) {}//references and const members must be used in this form. }; void Main () { A obja; cout<<obja.a<<Endl;}

#include <iostream.h>classa{ Public:    Const intA; A (intx): A (x) {}};classB: Publica{ Public: B (intx): A (x) {}};voidMain () {A Obja (2); B OBJB (3); cout<<obja.a<<Endl; cout<<objb.a<<Endl;}

How a const member or reference member must initialize a list by using a constructor

Related Article

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.