What is the best way to indicate that a double value has not been initialized?

前端 未结 9 1924
萌比男神i
萌比男神i 2020-12-22 06:26

I have a class CS which is to represent the co-ordinate system in 3D i.e.(x, y, z)

class CS
{
  private:
        double x;
        double y;
        double z         


        
9条回答
  •  一生所求
    2020-12-22 07:12

    Primarily, i want to manually assign 0x000000 address to any variable(int or double or char) without using pointers. any suggestions?

    That's not what you want. What you want is the ability to detect whether a variable has been set or not.

    Others have suggested things like using a specific floating-point value to detect the uninitialized state, but I suggest employing Boost.Optional. Consider:

    class CS
    {
      private:
        boost::optional x;
        boost::optional y;
        boost::optional z;
    }
    

    boost::optional either stores the type you give to the template parameter or it stores nothing. You can test the difference with a simple boolean test:

    if(x)
    {
      //Has data
    }
    else
    {
      //Has not been initialized
    }
    

    The downside is that accessing the data is a bit more complex:

    x = 5.0; //Initialize the value. x now has data.
    y = 4.0 * x; //Fails. x is not a double; it is an optional.
    y = 4.0 * (*x); //Compiles, but only works at runtime if x has a value.
    

提交回复
热议问题