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

前端 未结 9 1870
萌比男神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:04

    I want that the user can create a CS (0, 0, 0). In the constructor i want to initialise the address of x, y & z to NULL. this is to differentiate between the user defined (0, 0, 0) & the default value. I am creating the objects of CS dynamically, so there is no point in using the following code:

    This is the problem. Firstly, default value? What default value? Why should there be a default value? That's wrong. And secondly, it's fundamentally impossible for you to change the address of any variable.

    What you want cannot be done and even if it could, it would be a horrendously bad idea.

    0 讨论(0)
  • 2020-12-22 07:06

    You can't change the address of a variable. And you can't assign pointer values (like NULL, or nullptr in C++) to a variable of a non-pointer type, such as double.

    0 讨论(0)
  • 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<double> x;
        boost::optional<double> y;
        boost::optional<double> 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<double>.
    y = 4.0 * (*x); //Compiles, but only works at runtime if x has a value.
    
    0 讨论(0)
提交回复
热议问题