Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ - Conversion from Custom Classes to built in types

Tags:

c++

casting

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?

like image 630
jimifiki Avatar asked Aug 30 '13 13:08

jimifiki


1 Answers

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; 
};
like image 132
jrok Avatar answered Oct 23 '22 07:10

jrok