C + + operator overloaded conversion operator

Source: Internet
Author: User
Tags constructor

Why do I need a conversion operator?

We know that for built-in types of data we can convert data by forcing the use of a translator, such as (int) 2.1f; a custom class is also a type, so objects in a custom class also need to support this operation in many cases, and C + + provides a conversion operator overloaded function. It makes it possible to strongly convert a custom class object.

Conversion operators are more specific in their life style, as follows:

Operator class name ();

The overloaded function of a conversion operator has no return type, and it is the same as the constructor of the class, which does not follow the rule that the function has a return type, and they do not return a value.

Let me look at an example to see how it works:

Example 1

//Program Author: Junning 
//site: www.cndev-lab.com
//All manuscripts have copyright, if you want to reprint, please be sure to famous source and author
#include <iostream>
using namespace Std;
Class Test
{
Public:
Test (int a = 0)
{
cout<<this<< ":" <& lt; " Load Constructor! " <<a<<endl;
Test::a = A;
}
Test (test &temp)
{
cout<< "load copy constructor!" <<endl;
Test::a = Temp.a;
}
~test ()
{
cout<<this<< ":" << "Load destructor!" <<this->a<<endl;
Cin.get ();
}
Operator int ()//conversion operator
{
cout<<this<< ": <<" Load conversion operator Function! " <<this->a<<endl;
return test::a;
}
Public:
int A;
};
Int main ()
{
Test b;
cout<< "B's memory address" <<&b<<endl;
cout<< (int) b<<endl;//Strong conversion
System("pause");
}

In the example, we use the conversion operator to convert the object of the test class to the int type and output, pay attention to the operation State of the conversion operator function, and find that the temporary object is not produced, proving that it is not the same as the normal function, although it has a return statement.

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.