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

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

    One way to get the semantics of what you want would be to have the datatype of the coordinates be a type that carries with it a value indicating whether it has been assigned. Something like this.

    template
    class CoordinateValue {
       public:
           CoordinateValue() : uninitialized(true), val(0) {}
           CoordinateValue(T x) : uninitialized(false), val(x) {}
           void setVal(T x) {val = x; uninitialized= false}
           // Trivial getters
        private:
           T val;
           bool uninitialized;
    };
    

    I'd prefer something like this over cuter methods unless memory is really scarce for some reason.

    If the coordinates are either all default or all set, then you can have a single flag rather than a coordinate datatype that includes the flag.

提交回复
热议问题