这个operator []函数的实现如何工作? [英] How does this implementation of operator[] function work?

查看:83
本文介绍了这个operator []函数的实现如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一本书(Eric Lengyel的游戏引擎开发基础),并且该书用c ++编写了一些矢量操作,以下是代码段:

  struct Vector3D 
{
float x,y,z;

Vector3D()=默认值;

Vector3D(浮点a,浮点b,浮点c)
{
x = a;
y = b;
z = c;
}

float&运算符[](int i)
{
return((& x)[i]);
}
};

特别关注以下内容:

  float&运算符[](int i)
{
return((& x)[i]);
}

现在,无论输入什么索引,我都希望此代码返回x 。但是,根据输入输出相应的变量(x,y或z)。为什么是这样?谢谢您的帮助。

解决方案

暂时,让我们忽略函数实现方式的恶臭。 / p>

问题是,它如何工作?



如果您查看对象的成员变量,在班级中,当成员之间没有填充时,它们将按以下顺序放置在内存中:

  + ----- + ----- + ----- + 
| x | y | z |
+ ----- + ----- + ----- +

采用这种布局,对象看起来就像是一个 float s的数组。



如果使用:

  float * ptr =& x; 

ptr 指向这样的第一个元素



ptr [0] 计算结果为数组的第一个元素,与 x

ptr [1] 计算得出数组的第二个元素,即与 y 相同。

ptr [2] 计算得出数组的第三个元素,与 z 相同。



这就是为什么

  return((& x)[i ]); 

大部分时间都可以工作,即使这样的代码会导致标准中未定义的行为。


I am working through a book (Foundations Of Game Engine Development By Eric Lengyel) and the book is writing out some vector operations in c++, here is the snippet:

struct Vector3D
{
    float x, y, z;

    Vector3D() = default;

    Vector3D(float a, float b, float c)
    {
        x = a;
        y = b;
        z = c;
    }

    float& operator [](int i)
    {
        return((&x)[i]);
    }
};

im particularly concerned with this piece:

float& operator [](int i)
{
    return((&x)[i]);
}

Now I would expect this code to return x, no matter what index is entered. However the corresponding variable (x, y, or z) is output depending on the input. Why is this? Thanks for the help.

解决方案

For a few moments, let's ignore the foul smell of the way the function has been implemented.

The question is, how does it ever work?

If you look at the member variables of an object of the class, when there is no padding between members, they are laid out in memory as:

+-----+-----+-----+
|  x  |  y  |  z  |
+-----+-----+-----+

With such a layout, the object appears as though it is an array of floats.

If you use:

float* ptr = &x;

ptr points to the first element of such an array.

ptr[0] evaluates to the first element of the array, which is the same as x.
ptr[1] evaluates to the second element of the array, which is the same as y.
ptr[2] evaluates to the third element of the array, which is the same as z.

That's why

return((&x)[i]);

works most of the time, even though such code is cause for undefined behavior per the standard.

这篇关于这个operator []函数的实现如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆