C ++ Summary of precautions related to "class" (7): Constructor

Source: Internet
Author: User

1. We can provide a default real parameter for the constructor parameters.

Class account {
Public:
// Default constructor
Account ();
 
// The parameter name in the Declaration is not required
Account (const char *, double = 0.0 );
Const char * Name () {return _ name ;}
 
//...
 
PRIVATE:
//...
};

The following are two valid account class object definitions, which pass one or two real parameters to the constructor:

 

Int main ()
{
// OK: Both parameters are called.
Account Acct ("Ethan stern ");
Account * pact = new account ("Michael Lieberman", 5000 );
 
If (strcmp (Acct. Name (), PACT-> name ()))
//...
}

 

2. constructor form

 

// Recommended constructor form
Account acct1 ("Anna press ");

A common mistake for new C ++ language beginners is to declare an object initialized using the default constructor as follows:

// Oh! Not working as expected
Account newaccount ();

It can be compiled, but when we try to use it

// Compilation Error
If (! Newaccount. Name ())...

The compiler will complain that we cannot apply the member accessors to the function and define

// Defines a function newaccount,
// Not an account object
Account newaccount ();

It is interpreted by the compiler as defining a function that does not have a parameter and returns an account-type object-not our intention at all. The correct declaration of initializing class objects using the default constructor removes the trailing parentheses.

// OK: defines a Class Object
Account newaccount;

Only when no constructor or default constructor is declared can we define class objects without specifying real parameters. If you define a constructor with parameters, you 'd better define a default constructor:

 

// Default account Constructor
Inline account ::
Account (){
_ Name = 0;
_ Balance = 0.0;
_ Acct_nmbr = 0;
}

 

3. Member initialization table

 

Class initialization has a replaceable syntax. The member initialization table (member initialization list) is a list of member names and their initial values separated by commas. For example. The default account constructor can be written as follows:

// Use the default account constructor of the member initialization table
Inline account: Account ()
: _ Name (0 ),
_ Balance (0.0), _ acct_nmbr (0)
{}

 

The member initialization table can only be specified in the constructor definition, rather than in its declaration. The initialization table is placed between the parameter table and the constructor body, starting with a colon. The following is a two-parameter constructor, which partially uses the member initialization table:


Inline account ::
Account (const char * Name, double opening_bal)
: _ Balance (opening_bal)
{
_ Name = new char [strlen (name) + 1];
Strcpy (_ name, name );
 
_ Acct_nmbr = get_unique_acct_nmbr ();
}

 

4. the constructor is used as the conversion operator.

 

Consider the following:ProgramSection:

// In a header file
Extern void print (const account & ACCT );
 
//...
 
Int main ()
{
// Convert "oops" into an account object
// Use account: Account ("oops", 0.0)
Print ("oops ");
 
//...
}

By default, a single-parameter constructor or constructor has multiple parameters (except the first parameter, all other default real parameters) used as conversion operators. Print () in the call, the account constructor is implicitly applied by the compiler to convert a text string into an account object, although this conversion is not appropriate in this case.

Unintentional implicit class conversion, such as converting oops into an account object, has proved to be a hard-to-trace error source, the keyword explicit is introduced to Standard C ++ to help suppress this undesirable compiler-assisted behavior. The explicit modifier notifies the compiler not to provide implicit conversion:

Class account {
Public:
Explicit account (const char *, double = 0.0 );
//...
};

Explicit can only be applied to constructors.

 

5. copy constructors

 

Initializing another object of this class with one class object is called default memberwise initialization. In terms of concept, copying a class object to another class object is achieved by copying each non-static data member in sequence.

By default, initialization by members is often inappropriate for the correct behavior of classes. by defining an explicit instance of the copy constructor, we can change the default behavior, our account class requires us to do this, otherwise the two account objects will have the same account, which is obviously not allowed in this class specification.
A copy constructor has a reference to a class object as a form parameter, which is traditionally declared as Const. The following is its implementation:

 

Inline account ::
Account (const accout & RHs)
: _ Balance (RHS. _ balance)
{
_ Name = new char [strlen (RHS. _ name) + 1];
Strcpy (_ name, RHS. _ name );
 
// You cannot copy RHS. _ acct_nmbr.
_ Acct_nmbr = get_unique_acct_nmbr ();
}
When we write
Account acct2 (acct1 );

The compiler determines whether an explicit copy constructor is declared for the Account class. If the copy constructor is declared and accessible, it is called; if the copy constructor is declared but not accessible, acct2 is defined as a compilation time error. If the copy constructor instance is not declared, default initialization by members is executed. If we introduce or remove the declaration of a copy constructor later, the user program does not need to be changed. However, we need to recompile them.

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.