How to overload operators with a built-in return type?

后端 未结 4 824
时光说笑
时光说笑 2021-01-23 06:56

Say I have a class, that wraps some mathematic operation. Lets use a toy example

class Test
{
public:
   Test( float f ) : mFloat( f ), mIsInt( false ) {}

   fl         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-23 07:35

    You already have one implicit conversion from float to Test, in the form of the convert constructor

    class Test
    {
    public:
     /* ... */
    Test( float f ) : mFloat( f ) /*...*/ {}       
    
    };
    

    Which will support conversions such as:

    Test t(0.5f);
    

    You will likely also want a copy-assignement operator in order to make further implicit conversions from float to Test possible:

    class Test
    {
    public:
    
        Test& operator=(float f) { mFloat = f; return *this; }  
    };
    
    t = 0.75; // This is possible now
    

    In order to support implicit conversion from Test to float you don't use operator=, but a custom cast operator, declared & implemented thusly:

    class Test
    {
    public:
      /* ... */
      operator float () const { return mFloat; }
    };
    

    This makes implicit conversions posslible, such as:

    float f = t;
    

    As an aside, you have another implicit conversion happening here you may not even be aware of. In this code:

    Test t( 0.5 );
    

    The literal value 0.5 isn't a float, but a double. In order to call the convert constructor this value must be converted to float, which may result in loss of precision. In order to specify a float literal, use the f suffix:

    Test t( 0.5f );
    

提交回复
热议问题