In C ++, there is a special method to overload operators-type conversion Operator overloading, such:Operator type ();
Type can be a basic type or a class type.
/* <Br/> * type_conv.cpp <br/> * created on: 2009-8-14 <br/> * Author: kwarph <br/> * mail: kwarph@gmail.com <br/> */<br/> # include <iostream> </P> <p> using namespace STD; </P> <p> class horse <br/> {<br/> Public: <br/> horse (): weight (0), speed (0 ), teeth (0) <br/>{< br/>}</P> <p> horse (const Int & W, const Int & S, const Int & t = 0): weight (W), speed (S), teeth (t) <br/>{< br/>}</P> <p> void neigh () cons T <br/> {<br/> cout <"! "<" Weight: "<weight <", Running Speed: "<speed <Endl; <br/>}</P> <p> // other member functions... </P> <p> PRIVATE: <br/> int weight; <br/> int speed; <br/> int teeth; </P> <p> // other member variables... </P> <p >}; </P> <p> class deer <br/>{< br/> Public: <br/> deer (): weight (0), speed (0) <br/>{< br/>}</P> <p> deer (const Int & W, const Int & S ): weight (W), speed (S) <br/>{< br/>}</P> <p> operator horse () const // here <br/>{< br/> return hor Se (weight, speed); <br/>}</P> <p> operator int () const // here <br/>{< br/> return weight + speed; <br/>}</P> <p> void speak () const <br/> {<br/> cout <"I Am a deer with a fake package" <Endl; <br/>}</P> <p> // other member functions... </P> <p> PRIVATE: <br/> int weight; <br/> int speed; </P> <p> // other member variables... </P> <p >}; </P> <p> void listen (const Horse & H) <br/>{< br/> H. neigh (); <br/>}</P> <p> int main () <br/>{< br/> deer D (40, 68 ); // This is a deer, 4 0kg weight, running speed of 68 km per hour <br/> D. speak (); // do not believe what he said: I am a fake deer </P> <p> listen (d); // here, the deer turned into a horse and heard him scream: <br/> // I am a horse! Weight: 40, Running Speed: 68 </P> <p> // worse, a deer can also be converted into an int. Otherwise, how can he be associated with an int? The entire article "Harry Potter" <br/> int n = 12 + D; // 12 + 40 + 68 = 120 <br/> cout <n <Endl; // 120 <br/>}< br/>
Another example:
Class cdemo <br/>{< br/> Public: <br/> cdemo (int x, int y) <br/>{< br/> This-> _ x = x; <br/> This-> _ y = y; <br/>}< br/> operator int () <br/> {// Operator Overloading <br/> return _ x; <br/>}< br/> PRIVATE: <br/> int _ x; <br/> int _ y; <br/> }; <br/> int _ tmain (INT argc, _ tchar * argv []) <br/>{< br/> cdemo demo ); <br/> cout <demo <Endl; <br/> return 0; <br/>}