c++ - Conversion from Custom Classes to built in types
c++, casting
Solution
With a type conversion function:
class MyInt{
public:
MyInt(int x){theInt = x /10;}
int operator+(int x){return 10 * theInt + x;}
operator int() const { return theInt; } // <--
private
int theInt;
};
Problem
For the sake of clarity Let my new class be: ``` class MyInt{ public: MyInt(int x){theInt = x /10;} int operator+(int x){return 10 * theInt + x;} private int theInt; }; ``` let's say I want to be able to define: ``` MyInt Three(30); int thirty = Three; ``` But in order to get this result I'm writing: ``` MyInt Three(30); int thirty = Three + 0; ``` how can I get automatic conversion from my Custom class to a built-in type?