fork download
  1. #include <stdio.h>
  2.  
  3. #define USE_CAST_OP
  4.  
  5. class Float;
  6. class Double
  7. {
  8. double m_Value;
  9. public:
  10. Double() : m_Value( 0.0 ){}
  11. explicit Double( double d ) : m_Value( d ){}
  12. #ifdef USE_CAST_OP
  13. explicit
  14. #endif
  15. Double( const Float& f );
  16. double GetValue( void ) const { return m_Value; }
  17. Double operator +( const Double& other ){ printf( "Double::operator+(Double)\n" ); return Double( m_Value + other.m_Value ); }
  18. #ifdef USE_CAST_OP
  19. operator Float();
  20. #endif
  21. };
  22. class Float
  23. {
  24. float m_Value;
  25. public:
  26. Float() : m_Value( 0.0f ){}
  27. explicit Float( float f ) : m_Value( f ){}
  28. #ifdef USE_CAST_OP
  29. explicit
  30. #endif
  31. Float( const Double& d ) : m_Value( d.GetValue() ){}
  32. float GetValue( void ) const { return m_Value; }
  33. Float operator +( const Float& other ){ printf( "Float::operator+(Float)\n" ); return Float( m_Value + other.m_Value ); }
  34. Double operator +( const Double& other ){ printf( "Float::operator+(Double)\n" ); return Double( m_Value + other.GetValue() ); }
  35. #ifdef USE_CAST_OP
  36. operator Double(){ printf( "Float to Double\n" ); return Double(); }
  37. #endif
  38. };
  39.  
  40. Double::Double( const Float& f ) : m_Value( f.GetValue() ){}
  41. #ifdef USE_CAST_OP
  42. Double::operator Float(){ printf( "Double to Float\n" ); return Float(); }
  43. #endif
  44.  
  45. // Double operator +( Double left, Double right ){ printf( "::operator+(Double,Double)\n" ); return Double(); }
  46.  
  47. void PrintType( const Double& d ){ printf( "Result : Double\n" ); }
  48. void PrintType( const Float& f ){ printf( "Result : Float\n" ); }
  49.  
  50. void RequireFloat( const Float& f ){ }
  51. void RequireDouble( const Double& d ){ }
  52.  
  53. int main( void )
  54. {
  55. Double d;
  56. Float f;
  57.  
  58. printf( "[0]\n" );
  59. PrintType( f + f );
  60.  
  61. printf( "[1]\n" );
  62. PrintType( d + d );
  63.  
  64. printf( "[2]\n" );
  65. PrintType( d + f ); // fはDoubleへ暗黙の型変換が発生する。
  66.  
  67. printf( "[3]\n" );
  68. PrintType( f + d ); // fはDoubleへ暗黙の型変換が発生する。
  69.  
  70. printf( "[4]\n" );
  71. RequireFloat ( d );
  72. RequireDouble( f );
  73.  
  74. return 0;
  75. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
[0]
Float::operator+(Float)
Result : Float
[1]
Double::operator+(Double)
Result : Double
[2]
Float to Double
Double::operator+(Double)
Result : Double
[3]
Float::operator+(Double)
Result : Double
[4]
Double to Float
Float to Double