2

我偶然发现了这门课:

class Vec3f
{
    ...
    float x, y, z;
    ...
};

inline float operator[](const int index) const
{
    return (&x)[index];
}

inline float& operator[](const int index)
{
     return (&x)[index];
}

该类使用 [] 访问数组中的 x、y、z 值,因此 v[0] 是 x 中的值,v[1] 是 y 中的值,v[2] 是z,但是

  • return 语句是如何工作的?
  • 读成这样是否正确:“从x的地址开始获取索引指定的地址中的值”?
  • do (&x) 必须在括号中,否则它会返回 x[index] 的地址的值,不是吗?
4

1 回答 1

4

从技术上讲,这不是有效的代码。

但是发生了什么:

// Declare four variables
// That are presumably placed in memory one after the other.
float x, y, z;

在代码中:

return (&x)[index];

// Here we take the address of x (thus we have a pointer to float).
// The operator [] when applied to fundamental types is equivalent to 
// *(pointer + index)

// So the above code is
return *(&x + index);
// This takes the address of x. Moves index floating point numbers further
// into the address space (which is illegal).
// Then returns a `lvalue referring to the object at that location`
// If this aligns with x/y/z (it is possible but not guaranteed by the standard)
// we have an `lvalue` referring to one of these objects.

使这项工作很容易并且合法:

class Vec3f
{
    float data[3];
    float& x;
    float& y;
    float& z;

    public:
        float& operator[](const int index) {return data[index];}

        Vec3f()
            : x(data[0])
            , y(data[1])
            , z(data[2])
        {}
        Vec3f(Vec3f const& copy)
            : x(data[0])
            , y(data[1])
            , z(data[2])
        {
            x = copy.x;
            y = copy.y;
            z = copy.z;
        }
        Vec3f& operator=(Vec3f const& rhs)
        {
            x = rhs.x;
            y = rhs.y;
            z = rhs.z;
            return *this;
        }
};
于 2013-08-18T23:05:20.743 回答