• Source
    1. #include <iostream>
    2. using namespace std;
    3.  
    4. class Temperature
    5. {
    6. public:
    7. //these static functions return a temporary object of type Temperature
    8. static Temperature Fahrenheit (double f);
    9. static Temperature Celsius (double c);
    10. static Temperature Kelvin (double k);
    11. //A static member function can't refer to non-static data.
    12. double getTemperature() { return _temp; }
    13. private:
    14. Temperature (double temp); //Constructor is private.
    15. double _temp;
    16. };
    17.  
    18. //_temp instantiated outside of Temparature class.
    19. Temperature::Temperature (double temp):_temp (temp) {}
    20.  
    21. Temperature Temperature::Fahrenheit (double f)
    22. { return Temperature ((f + 459.67) / 1.8); }
    23.  
    24. Temperature Temperature::Celsius (double c)
    25. { return Temperature (c + 273.15); }
    26.  
    27. Temperature Temperature::Kelvin (double k)
    28. { return Temperature (k); }
    29.  
    30. int main() {
    31. // We are initializing the objects created here via kelvin(), celsius() and fahrenheit()
    32. // to objects
    33. // kelvin, celsius and fahrenheit.
    34. Temperature kelvin = Temperature::Kelvin (300.0);
    35. Temperature celsius = Temperature::Celsius (26.85);
    36. Temperature fahrenheit = Temperature::Fahrenheit(80.33);
    37.  
    38. cout << "Entered kelvin " << kelvin.getTemperature () << endl;
    39. cout << "Entered celsius " << celsius.getTemperature () << endl;
    40. cout << "Entered fahrenheit " << fahrenheit.getTemperature () << endl;
    41.  
    42. return 0;
    43. }
    44.  
    45. /*
    46. Output:
    47.  
    48. Entered kelvin 300
    49. Entered celsius 300
    50. Entered fahrenheit 300
    51. */