Inquiry about class variable declarations in C++

前端 未结 6 1174
悲&欢浪女
悲&欢浪女 2021-01-19 00:43

I have a class to represent a 3D vector of floats:

class Vector3D
{
    public:

    float x, y, z;
    float * const data;

    Vector3D() : x(0.0), y(0.0),         


        
6条回答
  •  广开言路
    2021-01-19 01:37

    Your solution is not valid, but if you can ensure (or know) that your compiler will "do the right thing" (in particular by controlling padding between the x, y and z elements) you will be ok. In this case though I'd remove the data member altogether and use operator[].

    I've seen something like this used on occasion. It runs into exactly the same issues, but does save you storing that data pointer, and allows for a nicer v[0] syntax rather than v.data[0].

    class Vector3D
    {
        public:
    
        float x, y, z;
        float& operator[](int i) { return *(&x+i); }
        const float& operator[](int i) const { return *(&x+i); }
    
        Vector3D() : x(0.0), y(0.0), z(0.0) {}
    }
    

    EDIT: Prompted by ildjam heres a compliant version using accessors rather than members, that is similar.

    class Vector3D
    {
        public:
          float& operator[](int i) { return v[i]; }
          const float& operator[](int i) const { return v[i]; }
    
          float& x() { return v[0]; }
          float  x() const { return v[0]; }
          float& y() { return v[1]; }
          float  y() const { return v[1]; }
          float& z() { return v[2]; }
          float  z() const { return v[2]; }
    
          Vector3D() : v() {}
        private:    
          float v[3];
    };
    

提交回复
热议问题