An in-depth explanation of C + + data type conversion related functions of knowledge _c language

Source: Internet
Author: User
Tags function prototype

C + + data type conversions and transformation constructors
Conversions between standard data types

In C + +, some different types of data can be converted automatically, for example

  int i = 6;
  i = 7.5 + i;


The compiler system for 7.5 is treated as a double number, when the expression is solved, first converts 6 to double, and then 7.5, gets and 13.5, when assigning to integer variable I, converts 13.5 to integer 13, and then assigns to I. This conversion is done automatically by the C + + compilation system, and the user does not need to intervene. This transformation is called an implicit type conversion.

C + + also provides explicit type conversions, in which a program person specifies to convert a specified data to another specified type in the form of:

  Type name (data)


Such as

  Int (89.5)


The effect is to convert 89.5 to an integer of 89.

Previously we were exposed to the conversion between standard types, and now that the user has defined the class, a question has been raised: Can an object of a custom class be converted to a standard type? Can an object of a class be converted to an object of another class? For example, can a complex class of data be converted into integers or doubles? Can I convert an object of the date class to an object of the time class?

For standard types of conversions, the compiler system is rule-based and knows how to convert. For a user-declared type, the compiler does not know how to convert the system. The key to solving this problem is to let the compilation system know how to do these transformations, and to define specialized functions to handle.
Transformation Constructors

The function of a transformation constructor (conversion constructor function) is to convert a data of another type into an object of a class. Here's a review of several constructors you've learned before:
1) default constructor. Take the complex class as an example, the form of a function prototype is:

  Complex (); No parameters

2 constructor for initialization. The form of a function prototype is:

  Complex (Double R, double i); There are generally more than two parameters in the formal parameter list column

3 the copy constructor used to copy the object. The form of a function prototype is:

  Complex (Complex &c); A formal parameter is a reference to this class object

Now introduce a new constructor--the transformation constructor.

The transformation constructor has only one formal parameter, such as

  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 is 0. The user can define the transformation constructor as needed, and tell the compiler how to convert the system in the function body.

In a class body, you can have a transformation constructor, or you can have no transformation constructor, depending on your needs. Several of these constructors can appear in the same class at the same time, and they are overloads of constructors. The compilation system will match the constructor based on the number of arguments given when the object was established and the type to participate in the selection of the form.

If the above constructor is defined in the complex class, the following declaration statement is available in the scope of the complex class:

  Complex cl (3.5); To establish the object cl, because there is only one argument, call the transformation constructor


Establishes the Comptex class object CL, its real (actual part) value is 3.5,imag (imaginary part) the value is 0. Its role is to convert the double constant to a complex class object named CL. You can also use declarative statements to create an unnamed complex class object. Such as

  Complex (3.6);  Creating an unnamed object with a declaration statement is legal, but it cannot be used

You can use an anonymous object in an expression, such as:

  CL =complex (3.6);  Suppose CL is defined as a complex class object


Creates an unnamed complex class object with a value of (3.6+0i) and assigns the value of this nameless object to CL,CL after the value assigned is (3.6+0i).

If the operator "+" has been overloaded so that it can perform the addition of two complex class objects, if the following expression is present in the program:

  c = CL +2.5;


Compilation error because an Comptex class object and a floating-point number cannot be added with the operator "+". You can convert 2.5 to the complex class nameless object, and then add:

  c = cl + Complex (2.5);  Legal

Please compare complex (2.5) and int (2.5). The two forms are similar, int (2.5) is mandatory type conversion, 2.5 is converted to an integer, int () is a mandatory type conversion operator. It can be considered that complex (2.5) is also a force type conversion, converting 2.5 to a complex class object.

A transformation constructor is also a constructor that follows the general rules of the constructor. A constructor that has one parameter is usually used as a type conversion, so it is called a transformation constructor. In fact, a constructor with one parameter can also not be used as a type conversion, as

  Complex (Double R) {cout<<r;}//This usage is meaningless, no one will use it

The function body of the transformation constructor is determined by the user according to the need and must make it meaningful. For example, you can also define a transformation constructor:

  Complex (double R) {real =0; imag = r;}


That is, the real part is 0 and the imaginary part is R. This is not a violation of grammar, but no one will do so. Should conform to the habit, reasonable.

Note: A transformation constructor can have only one parameter. If you have more than one argument, you are not a transformation constructor. The reason is obviously, if there are more than one parameter, which argument is to convert to the object of the complex class?

To sum up, the method of converting a specified data to a class object using a transformation constructor is as follows:
1 declare a class first.

2 Define a constructor that has only one parameter in this class, the type of the parameter is the type that needs to be converted, and the method in the function body that specifies the transformation.

3 You can type conversions in the scope of the class in the following form:
Class name (data of the specified type)
You can convert data of the specified type to an object of this class.
Not only can you convert a standard type of data into a class object, you can also convert an object from another class to the class object that contains the transformation constructor. If you can convert a student class object to a teacher class object, you can write the following transformation constructor in the teacher class:

  Teacher (student& s) {num=s.num;strcpy (name, s.name); sex=s.sex;}


It should be noted, however, that the Num,name,sex in the object s must be a public member, otherwise it cannot be referenced outside the class.

C + + type conversion function (type conversion operator function)
The transformation constructor enables you to convert data of a specified type to an object of a class. However, you cannot convert an object of a class to a different type of data, such as converting a complex class object to a double type of data.

C + + provides a type conversion function (the type conversion function) to solve this problem. The role of a type conversion function is to convert an object of a class to another type of data. If you have declared a complex class, you can define the type conversion function in the complex class:

  Operator double ()
  {return real
    ;
  }


function returns the value of the double variable real. Its role is to convert a complex class object to a double 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 overload (the function name is operator + when the overloaded function of the operator "+" is defined).

The general form of a type conversion function is:

  operator type name ()
  {
    The statement that implements the transformation
  }


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

As you can see from the function form, it is similar to the operator overloading function, which starts with the keyword operator, but is overloaded with the type name. After overloading, the double type obtains new meaning in addition to its original meaning (converts a complex class object to the double type data and specifies the conversion method). In this way, the compiling system can not only recognize the original double data, but also treat the complex class object as double type.

Then the complex class pairs in the program have dual identities, both complex class objects and double type data. Complex class objects are converted only when needed, depending on the context of an expression. The transformation 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).

[Example] Use a simple example of a type conversion function.

#include <iostream>
using namespace std;
Class Complex
{public
:
  Complex () {real=0;imag=0;}
  Complex (double r,double i) {real=r;imag=i;}
  Operator double () {return real;}//Type conversion function
private:
  double real;
  Double imag;
};
int main ()
{
  Complex C1 (3,4), C2 (5,-10), C3;
  Double D;
  d=2.5+c1;//requires adding a double data to the complex class data
  cout<<d<<endl;
  return 0;
}

Analysis of the program:
1 If you do not define a type conversion function operator double in the complex class, the program compiles an error. Because you cannot implement the addition of double data to the complex class object. Now that you have defined a member function operator double, you can use it to convert complex class objects to double data. Note that you do not have to explicitly call a type conversion function in your program, it is automatically invoked, that is, an implicit invocation. Under what circumstances should a type conversion function be invoked? When compiling the system to handle expression 2.5 +cl, it is found that the left side of the operator "+" is a double data, while the right side is the complex class object, and the operator "+" overload function is not added directly, the compilation system discovers that there is an overloaded function on double, so call this function, Returns a double type, and then adds the data to 2.5.

2 If you add a statement to the main function:

  C3=C2;


At this time the compiler system is to C2 according to complex class object processing, or double type data processing? Since both sides of the assignment numbers are of the same type of data, they can be assigned legally, and there is no need to convert C2 to double data.

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

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


If you have a statement in the main function

  C3=C1+C2;


Because the operator "+" overload has been applied to the addition of two complex class objects, the C1 and C2 are processed by the complex class object, added to the same object C3. If instead

  D=C1+C2; D is a double type variable


Add the C1 to the C2 two class objects, and get a temporary complex class object, because it cannot assign to the double variable, but also the overloaded function of double, then call this function, convert the temporary class object to double data, and then assign to D.

As you can tell from the foregoing, the concepts and methods for overloading the type and overloading the operators are similar, and overloaded functions use the keyword operator. Therefore, a type conversion function is usually also called a type conversion operator function, and because it is also an overloaded function, it is also referred to as a type conversion operator overloaded function (or coercion type conversion operator overloaded function).

If the program needs to be a complex class object and a double variable +,-,*,/arithmetic operations, as well as relational and logical operations, if not the type conversion function, the various operators will be overloaded, so that various operations can be performed. In this way, is very troublesome, the workload is big, the procedure appears long. If you overload a double with a type conversion function (so that the complex class object is converted 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 is available using the various operators provided by the system.

[Example] contains programs that convert constructors, operator overloaded functions, and type conversion functions. Read the following program to include only transformation constructors and operator overloading functions in this program.

#include <iostream>
using namespace std;
Class Complex
{public
:
  Complex () {real=0;imag=0;}//default constructor
  Complex (double R) {real=r;imag=0;} Convert constructor
  Complex (double r,double i) {real=r;imag=i;} The constructor that implements the initialization
  friend Complex operator + (Complex c1,complex C2);//overloaded operator "+" friend function
  void display ();
Private:
  double real;
  Double imag;
};
Complex operator + (Complex C1,complex c2)//define operator "+" overloaded function
{return
  Complex (c1.real+c2.real, C1.imag+c2.imag) ;
}
void Complex::d isplay ()
{
  cout<< "(" <<real<< "," <<imag<< "i)" <<endl;
}
int main ()
{
  Complex C1 (3,4), C2 (5,-10), C3;
  c3=c1+2.5; The plural and double data are added
  c3.display ();
  return 0;
}

Note that when running in Visual C + + 6.0 environments, the first line must be changed to #include <iostream.h>, and the 2nd line is deleted, otherwise the compilation cannot pass.

Analysis of the program:
1 if the transformation constructor is not defined, the program compiles an error.

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

  operator+ (c1, 2.5)

Since 2.5 is not a complex class object, the system first invokes the transformation constructor complex (2.5) to establish 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 and (2.5+0i) and assign to C3. Run result is

  (5.5+4i)


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

To get an important conclusion, the operator "+" function is overloaded as a friend function in case 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. Operator functions cannot be overloaded as member functions when the first operand is not a class object. If the operator "+" function is overloaded as a member function of a class, the Exchange law does not apply.

For this reason, the binocular operator function is generally overloaded as a friend function. The monocular operator is overloaded as a member function.

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

  Friend Operator+ (Double, Complex &);


Obviously this is not convenient, or it is convenient to overload the binocular operator function as a friend function.

5 Add the type conversion function on the basis of the above program:

  Operator double () {return real;}


At this point the common part of the complex class is:

  Public:
  Complex () {real=0;imag=0}
  Complex (Double R) {real=r;imag=0;}//Convert constructor
  Complex (double r,double i) {real=r;imag=i;}
  Operator double () {return real;} Type conversion function
  friend Complex operator+ (Complex c1,complex C2);//overloaded operator "+"
  void display ();

The remaining parts are unchanged. The program failed at compile time because of two semantics.

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.