Conversion operator : overload conversion operator « Operator Overloading « C++ Tutorial






#include <iostream>
 
 class MyType
 {
 public:
     MyType();
     MyType(int val);
     ~MyType(){}
     int getValue()const { return myValue; }
     void setValue(int x) {myValue = x; }
     operator unsigned short();
 private:
     int myValue;
 };
 
 MyType::MyType():myValue(0) {}
 
 MyType::MyType(int val): myValue(val) {}
 
 MyType::operator unsigned short ()
 {
     return ( int (myValue) );
 }
 
 int main()
 {
     MyType ctr(5);
     int theShort = ctr;
     std::cout << "theShort: " << theShort << std::endl;
     return 0;
 }
theShort: 5








10.5.overload conversion operator
10.5.1.Conversion operator