fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Kelvin;
  5.  
  6. class TemperatureUnit
  7. {
  8. public:
  9. explicit TemperatureUnit(int value) :
  10. m_value(value)
  11. {
  12. }
  13.  
  14. virtual void print() = 0;
  15.  
  16. int value() const
  17. {
  18. return m_value;
  19. }
  20. private:
  21. int m_value;
  22. };
  23.  
  24. class Celsius : public TemperatureUnit
  25. {
  26.  
  27. public:
  28. Celsius(int value) :
  29. TemperatureUnit(value)
  30. {
  31.  
  32. }
  33. void print() override
  34. {
  35. cout<<value()<<"[C]\n";
  36. }
  37.  
  38. Celsius operator +(const Kelvin& kelvin);
  39.  
  40. };
  41.  
  42. class Kelvin : public TemperatureUnit
  43. {
  44.  
  45. public:
  46. Kelvin(int value) :
  47. TemperatureUnit(value)
  48. {
  49.  
  50. }
  51.  
  52. void print() override
  53. {
  54. cout<<value()<<"[K]\n";
  55. }
  56.  
  57. Kelvin operator +(const Celsius& celsius);
  58. };
  59.  
  60. //operator definitions
  61. Celsius Celsius::operator +(const Kelvin& kelvin)
  62. {
  63. Celsius c(this->value() + kelvin.value() - 273);
  64. return c;
  65. }
  66.  
  67. Kelvin Kelvin::operator +(const Celsius& celsius)
  68. {
  69. Kelvin k(this->value() + celsius.value() + 273);
  70. return k;
  71. }
  72.  
  73. int main() {
  74. Kelvin kelvin(293);
  75. Celsius celsius(20);
  76.  
  77. (celsius + kelvin).print();
  78. (kelvin + celsius).print();
  79.  
  80.  
  81. return 0;
  82. }
Success #stdin #stdout 0s 15224KB
stdin
Standard input is empty
stdout
40[C]
586[K]