C + + conversion constructors and implicit conversion functions ~ Reprint

Source: Internet
Author: User
Tags function prototype

Original address: C + + conversion constructors and implicit conversion functions

The transformation constructor allows you to convert data of a specified type into an object of a class. However, 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.

C + + provides type conversion functions (the type conversion function) to solve this problem. The function of a type conversion function is to convert an object of one class into 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 function returns the value of the double-type variable real. Its purpose is to convert a complex class object to a double type of data whose value is the value of the data member real in the complex class. Note that the function name is operator double, which is consistent with the operator overloading (when defining an overloaded function for operator "+", the function name is operator +).

    operator type name ()    {        The statement implementing the Transformation    }

The function type cannot be specified before the function name, and the function has no arguments. The type of its return value is determined by the type name specified in the function name. A type conversion function can only be used as a member function, because the body of the transformation is an object of this class. Cannot be a friend function or a normal function.


As you can see from the function, it is similar to the operator overloading function, which begins with the keyword operator, except that the type name is overloaded. After overloading the double type, it obtains a new meaning in addition to the original meaning (converting a complex class object to a double type data and specifying a conversion method). In this way, the compilation system can not only recognize the original double data, but also the complex class object as a double data processing.

Then the complex class in the program has a dual identity, which is both a complex class object and a double type of data. The complex class object is converted only when needed, and is determined by the context of the expression. Conversion constructors and type conversion operators have a common function: when needed, the compilation system automatically calls these functions, creating an unnamed temporary object (or temporary variable).

[Example 10.9] A simple example of using a type conversion function.

#include <iostream>using namespacestd; #include<iostream>using namespacestd;classComplex { Public: Complex () {Real=0; imag=0;} Complex (DoubleRDoublei) {real=r;imag=i;} operator Double( ) {returnReal;}//type conversion function Private:     DoubleReal; Doubleimag;}; intMain () {Complex C1 (3,4), C2 (5,-Ten), C3; DoubleD; D=2.5+C1;//requires the addition of a double data to the complex class datacout<<d<<Endl; return 0; }

Analysis of the program:

1) If the type conversion function operator Double is not defined in the complex class, the program compiles an error. Because the addition of the double type data to the complex class object cannot be implemented. Now that you have defined the member function operator double, you can use it to convert the complex class object to a double type of data. Note that you do not have to explicitly invoke a type conversion function in your program, which is called automatically, that is, implicitly. Under what circumstances do you invoke a type conversion function? When the compiling system deals with Expression 2.5 +cl, it is found that the left side of the operator "+" is double, while the right side is the complex class object, without the operator "+" overloaded function, which cannot be added directly, and the compiled system discovers an overloaded function for double, so call this function. Returns a double type of data, and then adds it to 2.5.

2) If you add a statement to the main function:
C3=C2;
Ask at this time to compile the system is C2 by complex class object processing it, or double type data processing? Since the assignment number is on both sides of the same class of data, it is possible to legally assign the value, there is no need to convert C2 to double type data.

3) If the overloaded operator "+" function is declared as a friend function in the complex class:

    operator+ (Complex c1,complex c2)// define operator "+" overloaded function     {        return Complex (c1.real+c2.real, c1.imag+c2.imag);    }

If there is a statement in the main function

C3=C1+C2;
Because the operator "+" is overloaded, so that it can be used for the addition of two complex class objects, C1 and C2 are processed by the complex class object, and the added value is assigned to the same object C3. If you change to
D=C1+C2; D is a double type variable
Add C1 and C2 two class objects, get a temporary complex class object, because it can not be assigned to a double variable, and a double overloaded function, so call this function, the temporary class object is converted to double data, and then assigned to D.

As you can tell from the previous introduction, the overloads of the types and the concepts and methods of overloading the operators are similar, and the overloaded functions use the keyword operator. Therefore, a type conversion function is also known as a type conversion operator function, because it is also overloaded, so it is also called a type conversion operator overload function (or coercion type conversion operator overload function).

If a complex class object and a double type variable are required to perform arithmetic operations such as +,-,*,/, as well as relational and logical operations, it is necessary to overload a variety of operators without a type conversion function so that various operations can be performed. In this way, it is very troublesome, the workload is large, the program looks lengthy. If you overload a double with a type conversion function (to convert the complex class object to double data), you do not have to overload the various operators because the complex class object can be automatically converted to double data, and the operation of the standard type of data It is possible to use the various operators provided by the system.

[Example 10.10] contains a program that transforms constructors, operator overloading functions, and type conversion functions. Read the following program, which contains only the transformation constructors and operator overloading functions in this program.

#include <iostream>using namespacestd;classComplex { Public: Complex () {Real=0; imag=0;}//default constructorComplex (DoubleR) {real=r;imag=0;}//Conversion ConstructorsComplex (DoubleRDoublei) {real=r;imag=i;}//constructors that implement initializationFriend Complexoperator+ (Complex C1,complex C2);//friend function for overloaded operator "+"     voiddisplay ();Private:     DoubleReal; Doubleimag;}; Complexoperator+ (Complex C1,complex C2)//define operator "+" overloaded functions {     returnComplex (C1.real+c2.real, c1.imag+C2.imag); } voidComplex::d isplay () {cout<<"("<<real<<","<<imag<<"i)"<<Endl;} intMain () {Complex C1 (3,4), C2 (5,-Ten), C3; C3=c1+2.5;//add complex numbers to double dataC3.display (); return 0; }

Note that when running in the Visual C + + 6.0 environment, you need to change the first line to # include <iostream.h>, and delete the 2nd line, or the compilation will not pass.


Analysis of the program:
1) If no conversion constructor is defined, this program compiles an error.

2) Now, the transformation constructor is defined in class complex and specifies how to form a complex number. Since the operator "+" has been overloaded, the compilation system interprets the expression c1+2.5 as

    operator 2.5)

Since 2.5 is not a complex class object, the system first calls the transformation constructor complex (2.5) and establishes a temporary complex class object with a value of (2.5+0i). The function call above is equivalent to

    operator+ (C1, Complex (2.5))

Add C1 with (2.5+0i) and assign to C3. Run the result as

    (5.5+4i)

3) If you put "c3=c1+2.5;" Changed to C3=2.5+C1; Programs can be compiled and run correctly. The process is the same as before.


An important conclusion is given that the operator "+" function is overloaded as a friend function when the corresponding transformation constructor has been defined, and the commutative law can be used when the two complex numbers are added.

If an operator function is overloaded with a member function, its first argument must be an object of this class. You cannot overload an operator function with a member function when the first operand is not a class object. If you overload the operator "+" function as a member function of a class, the Exchange law does not apply.

For this reason, it is common to overload the binocular operator function with a friend function. The monocular operator is overloaded as a member function.

4) If you must overload an operator function with a member function, and the first operand is not a class object, there is only one way to resolve it, and then you overload an operator "+" function with the first argument being a double type. Of course, this function can only be a friend function, the function prototype is

    operator+ (double, Complex &);

Obviously this is inconvenient, or it is convenient to overload the binocular operator function with the friend function.


5) Add the type conversion function based on the above program:

operator Double () {return real;}

At this point the common parts of the complex class are:

   Public: Complex () {Real=0; imag=0;} Complex (DoubleR) {real=r;imag=0;}//Conversion ConstructorsComplex (DoubleRDoublei) {real=r;imag=i;} operator Double( ){returnReal;}//type conversion functionFriend Complexoperator+ (Complex C1,complex C2);//overloaded operator "+"   voidDisplay ();

The rest of the section does not change. The program failed at compile time because of the two semantics.

C + + conversion constructors and implicit conversion functions ~ Reprint

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.