c++ - 在这种情况下,运算符 [ ] 重载如何工作?

标签 c++ overloading

我偶然发现了这个类(class):

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中的值,但是

  • 返回声明如何运作?
  • 这样理解是否正确:“获取从x的地址开始的索引指定的地址中的值”?
  • Do (&x) 必须在括号中,否则会返回 x[index] 的地址值,不是吗?

最佳答案

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

但是发生了什么:

// 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;
        }
};

关于c++ - 在这种情况下,运算符 [ ] 重载如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18310301/

相关文章:

c++ - 类模板中声明的友元函数的模板参数推导

c++ - 如何在 emacs 中使用公司模式、irony 后端和 irony header

c++ - 为什么这个函数指针赋值在直接赋值而不是使用条件运算符时起作用?

functional-programming - 在 Elm 中,你可以让一个函数具有多种类型吗?你能有一个重载的函数吗?

powershell - 如何重载 PowerShell 内置类的方法

c++ - 适合集合(图形)分区的数据结构

c++ - 如何避免直接链接到cmake中的库文件?

c++重载方法参数与原始方法的参数派生类

java - 多态性和方法重载

c++ - 如何通知一个小部件有关 Qt 中另一个小部件的更改?