Units of measurement in C++

后端 未结 3 1725
后悔当初
后悔当初 2021-02-02 14:42

I\'m working on a game engine, and currently I\'m stuck designing the IO system. I\'ve made it so, the engine itself doesn\'t handle any file formats, but rathe

3条回答
  •  滥情空心
    2021-02-02 15:29

    You can use the factory design pattern to accomplish what you're looking for. You can create a frequency class with a private constructor and several static methods that will construct the object depending on the units the user wants to use. By keeping the constructor private, the user is forced to declare his units explicitly, which reduces the likelihood of user error.

    #include 
    
    using namespace std;
    
    class frequency
    {
    public:
      static frequency hertz(int hz)
      {
        return frequency(hz);
      }
    
      static frequency kilohertz(double kHz)
      {
        return frequency(kHz * KHZ_TO_HZ);
      }
    
      static frequency rpm(int rpm)
      {
        return frequency(rpm * RPM_TO_HZ);
      }
    
      int hz()
      {
        return m_hz;
      }
    
    private:
      static const int KHZ_TO_HZ = 1000;
      static const int RPM_TO_HZ = 60;
    
      frequency(int hz) : m_hz(hz)
      {
      }
    
      int m_hz;
    };
    
    int main()
    {
      wcout << frequency::hertz(44100).hz() << "Hz" << endl;
      wcout << frequency::kilohertz(44.100).hz() << "Hz" << endl;
    }
    

提交回复
热议问题