Conversion from built in types to Custom Classes

前端 未结 3 1359
不知归路
不知归路 2021-01-19 10:54

I have a custom class that acts as an int called Integer, I would like to tell compiler how to convert certain types to Integer automatically so that I can avoid typing same

相关标签:
3条回答
  • 2021-01-19 11:05

    Write a constructor that takes int, as:

    class Integer
    {
       public:
           Integer(int);
    };
    

    If the class Integer has this constructor, then you can do this:

    void f(Integer);
    
    f(Integer(1)); //okay 
    f(1);          //this is also okay!
    

    The explanation is that when you write f(1), then the constructor of Integer that takes a single argument of type int, is automatically called and creates a temporary on the fly and and then that temporary gets passed to the function!


    Now suppose you want to do exactly the opposite, that is, passing an object of type Integer to a function takes int:

     void g(int); //NOTE: this takes int!
    
     Integer intObj(1);
     g(intObj); //passing an object of type Integer?
    

    To make the above code work, all you need is, define a user-defined conversion function in the class as:

    class Integer
    {
       int value;
       public:
           Integer(int);
           operator int() { return value; } //conversion function!
    };
    

    So when you pass an object of type Integer to a function which takes int, then the conversion function gets invoked and the object implicity converts to int which then passes to the function as argument. You can also do this:

    int i = intObj; //implicitly converts into int
                    //thanks to the conversion function!   
    
    0 讨论(0)
  • 2021-01-19 11:24

    You could define constructors in Integer for those types you want to implicitly convert. Do not make them explicit.

    0 讨论(0)
  • 2021-01-19 11:29

    Nawaz has given the correct answer. I just want to point out someting. If the conversion operator is not const, you can't convert const objects

    const Integer n(5);
    int i = n; // error because non-const conversion operator cannot be called
    

    Better declare your conversion operator as

    operator int() const {return value;}
    
    0 讨论(0)
提交回复
热议问题