"C + + Primer Seventh" implicit class-type conversions

Source: Internet
Author: User

Conversion Constructors

Conversion Constructor : If the constructor accepts only one argument, it actually defines an implicit conversion mechanism for converting such types, and sometimes we call this constructor a transform constructor.

A constructor that can be called through an argument defines a rule that implicitly converts a parameter type from a constructor to a class type.

For example, in the Sales_data class, the constructor that accepts a string and the constructor that accepts IStream each define a rule that implicitly converts from both types to sales_data. In other words, where sales_data is needed, we can use string or IStream as an alternative:

  constructor: Sales_data ( const  string  &s); Sales_data (IStream  &); Sales_data  &combine (const  sales_data&  string  null_book= " 9-999-99999-9   ;item.combine (Null_                          //  construct a temporary Sales_data object  //  Units_sold and revenue of the object equals 0, Bookno equals Null_book  

Here we call the combine member of Sales_data with a string argument. When the call is valid, the compiler automatically creates a Sales_data object with the given string. The newly generated (temporary) Sales_data object is passed to combine. because the Combine parameter is a constant reference, we can pass the parameter to a temporary amount .

Only one-step type conversions are allowed

• The compiler will only perform one-step type conversions automatically.

For example, because the following code implicitly uses two conversion rules, it is wrong:

// //(2) then convert this (temporary) string to Sales_data item.combine ("    9-999-99999-9 ");

If we want to complete the above call, we can explicitly convert the string to a string or Sales_data object:

// correct: explicitly converted to string, implicitly converted to Sales_dataitem.combine (string("9-999-99999-9" )); // correct: implicitly converted to string, explicitly converted to Sales_dataitem.combine (Sales_data ("9-999-99999-9" ));
Type conversion is not always valid

The need to convert from string to sales_data depends on our perception of the user's use of the transformation. In this case, the conversion might be right. A string in Null_book may represent a non-existent ISBN number.

Another conversion from IStream to Sales_data:

// use the IStream constructor to create a function to pass to combineitem.combine (CIN);

This code implicitly converts CIN to Sales_data, which executes the Sales_data constructor that accepts a IStream. the The constructor creates a (temporary) Sales_data object by reading the standard input and then passes the resulting object to combine.

The Sales_data object is a temporary amount and we cannot access it once the combine is complete. In fact, we build an object that adds its value to item and then discards it.

suppress implicit conversions of constructor definitions

In the context of a program that requires implicit conversion, we can block by declaring the constructor as explicit:

1 classsales_data{2  Public:3Sales_data () =default;4Sales_data (ConstSTD::string&s,unsigned N,Doublep):5Bookno (s), Units_sold (n), Revenue (p*N) {}6     ExplicitSales_data (ConstSTD::string&s): Bookno (s) {}7     ExplicitSales_data (std::istream&);8     //other members are consistent with the previous9};

At this point, no constructor can be used to implicitly create the Sales_data object, and neither of the previous usages could be compiled:

Item.combine (Null_book);   // Error: String constructor is explicit Item.combine (CIN);   // Error: The IStream constructor is explicit    

• The keyword Explicit is valid only for one argument's constructor . constructors that require multiple arguments cannot be used to perform implicit conversions, and all of these constructors are not required to be specified as explicit .

• You can only use the explicit keyword when declaring a constructor within a class, and should not be duplicated when defined outside the class:

// error: The explicit keyword is allowed only at the constructor declaration within the class Explicit  is {Read (is, * this);}
explicit constructors can only be used for direct initialization

One case where an implicit conversion occurs is when we perform the initialization of the copy form (using =). At this point, we can only use direct initialization instead of using the explicit constructor:

Sales_data item1 (null_book);  // correct: Direct initialization Sales_data Item2=null_book;   // Error: The explicit constructor cannot be used for the initialization process of copy form

Note : When we declare a constructor using the explicit keyword, it will only be used as a direct initialization. Also, the compiler will not use the constructor during the automatic conversion process.

explicitly using constructors for transformations

Although the compiler does not use the explicit constructor for implicit conversion procedures, we use such constructors to explicitly force conversions "

// correct: The argument is an explicitly constructed Sales_data object Item.combine (Sales_data (Null_book)); // correct: static_cast can use explicit's constructor Item.combine (static_cast<sales_data> (CIN));

In the first call, we use the Sales_data constructor directly, which creates a temporary Sales_data object by accepting the constructor of the string. For the second invocation, we use static_cast to perform an explicit rather than implicit conversion. WhereStatic_cast uses the IStream constructor to create a temporary Sales_data object .

"C + + Primer Seventh" implicit class-type conversions

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.