Effective C + + clause 13-17 "Object Management Resources" C + + implicit conversion and conversion constructors

Source: Internet
Author: User

In fact, we have seen a number of standard-type data conversion between C + +, this form is used in the program to convert a specified data to another specified type, that is, a cast, such as: int a = INT (1.23), the effect is to convert 1.23 to shaping 1. However, for user-defined class types, the compilation system does not know how to convert, so you need to define specialized functions to tell the compiler how to convert the system, which is the conversion constructor and type conversion function!

Note: Conversion constructors, implicit conversions, and function objects do not confuse!!! A function object is an overloaded operator (), and an implicit conversion function is easy to confuse.


First, the conversion constructor

The conversion constructor (conversion constructor function) is the function of converting a different type of data into an object of a class?
When a constructor has only one parameter, and the parameter is not a const reference to this class, this constructor is called a transform constructor.
The conversion constructor is an overload of the constructor.
For example:
Complex (Double R)   {      real=r;      imag=0;  }  
The function is to convert the parameter r of the double type to the object of the complex class, and R as the real part of the complex number, and the imaginary part to 0? The user can define the conversion constructor as needed, and tell the compiler how to convert it in the function body.
So how do you use conversion constructors for type conversions? Let's look at the following example:

TypeSwitch.cpp: Defines the entry point of the console application.  //    #include "stdafx.h"  #include <iostream>    using namespace std;    Class Complex  {public  :      Complex (): Real (0), imag (0) {};      Complex (Double R, double i): Real (R), Imag (i) {};      Complex (Double R): Real (R), Imag (0) {};  Define conversion constructor        void Print () {          cout<< "real =" << real << "image =" <<imag<<endl;
   }      complex& operator+ (Complex c) {          return Complex (This->real + c.real, This->imag + c.imag);           }  private:      double real;      Double imag;  };    int main (int argc, _tchar* argv[])  {      Complex C;      c = 1.2;  Call the conversion constructor to convert 1.2 to complex Type      c.print ();      Complex C1 (2.9, 4.2);      Complex C2 = c1 + 3.1; Call the transform constructor to convert 3.1 to complex type      C2. Print ();      return 0;  }  

Not only can you convert a standard type of data into a class object, but you can also convert an object from another class to the class object where the transformation constructor resides? If you can convert a student class object to a teacher class object, you can write the following conversion constructor in the teacher class:
Teacher (student& s)  {      num=s.num;      strcpy (name,s.name);      Sex=s.sex;  }  
Use the same way!
Attention:
1. Use a transform constructor to convert data of a specified type to an object of a class? But you cannot turn an object of a class into a different type of data, such as converting a complex class object to a double type of data?
2. If you do not want the conversion constructor to take effect, that is, to deny other types from conversion constructors to this type, you can precede the conversion constructor with explicit! For example:

TypeSwitch.cpp: Defines the entry point of the console application.  //    #include "stdafx.h"  #include <iostream>    using namespace std;    Class Complex  {public  :      Complex (): Real (0), imag (0) {};      Complex (Double R, double i): Real (R), Imag (i) {};      Explicit Complex (Double R): Real (R), Imag (0) {};  Explicit Forbidden constructor conversion function        void Print () {          cout<< "real =" << real << "image =" <<imag<& Lt;endl;      }  Private:      double real;      Double imag;  };    int main (int argc, _tchar* argv[])  {      Complex C1 (1.2, 2.3), C2;      Double D;      D = c1 + 1.1; The call type conversion function converts C1 to double, compiling an error!      cout<<d<<endl;            return 0;  }   
Ii. type conversion function (implicit conversion function of Class)

Can a transformation constructor convert data of a specified type into an object of a class? But you cannot turn an object of a class into another type of data, such as converting a complex class object to a double type of data. and the type conversion function is specifically designed to solve this problem!
What is the function of a type conversion function to convert an object of one class to another type of data?
If you have declared a complex class, you can define a type conversion function in the complex class like this:

Operator double ()  {       return real;  }   
The general form of a type conversion function is:
operator type name ()
{
Statements that implement transformations
}
Precautions:
1. Cannot specify function type before function name, function has no parameters?
2. The type of the return value is determined by the type name specified in the function name?
3. The type conversion function can only be used as a member function, because the body of the transformation is an object of this class and cannot be a friend function or a normal function?
4. As you can see from the function, it is similar to the operator overloading function, which begins with the keyword operator, except that it is overloaded with the type name? After overloading the double type, it obtains new meanings in addition to the original meaning (converting a complex class object to a double type data, and specify the conversion method)? Thus, the compilation system can not only recognize the original double type data, but also the complex class object as a double data processing?
TypeSwitch.cpp: Defines the entry point of the console application.  //    #include "stdafx.h"  #include <iostream>    using namespace std;    Class Complex  {public  :      Complex (): Real (0), imag (0) {};      Complex (Double R, double i): Real (R), Imag (i) {};      Complex (Double R): Real (R), Imag (0) {};  Define conversion constructor        void Print () {          cout<< "real =" << real << "image =" <<imag<<endl;
   }      operator double () {//define type conversion function          return real;      }  Private:      double real;      Double imag;  };    int main (int argc, _tchar* argv[])  {      Complex C1 (1.2, 2.3);      Double D;      D = c1 + 1.1; Call the type conversion function to convert C1 to double      cout<<d<<endl;            return 0;  }  
In this case, for d = C1 + 1.1, call the type conversion function to convert the C1 to a double type and then add it to 1.1!
So the complex class in the program has a dual identity, both the complex class object and the double type data? Complex class objects are converted only when they are needed, depending on the context of the expression. The conversion constructor and the type conversion operator have a common function: when needed, the compilation system automatically calls these functions, creating an unnamed temporary object (or temporary variable)?

Effective C + + clause 13-17 "Object Management Resources" C + + implicit conversion and conversion constructors

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.