c++ - 这个运算符重载函数返回什么?

标签 c++ reference operator-overloading square-bracket

我有一个页面的以下列表:

#include "vector.h"

// An axis-aligned bounding box
class AABB
{
  public:
    VECTOR P; //position
    VECTOR E; //x,y,z extents

    AABB( const VECTOR& p, const VECTOR& e): P(p) ,E(e) {}

    // ...

    const SCALAR min( long i ) const
    {

      return ((AABB*)this)->P[i] - ((AABB*)this)->E[i];
    }
    // ...
};

现在我不明白的是,具有 long 值的 min() 访问了什么。 我查看了 vector.h,发现方括号运算符重载了:

class VECTOR
{
  public:
    SCALAR x,y,z; //x,y,z coordinates

    //...

    //index a component
    //NOTE: returning a reference allows
    //you to assign the indexed element
    SCALAR& operator [] ( const long i )
    {
      return *((&x) + i);
    }
    //...
};

后来它被用作:

// each axis
for( long i=0 ; i<3 ; i++ )
{
  if( A.max(i)<B.min(i) && v[i]<0 )
  {

那么为什么 x 值引用递增 i
如果这个问题很简单,请多多包涵,我还是菜鸟。如果这还不够,我可以提供实际来源

最佳答案

它没有递增。

&x  //<- address of member x
(&x) + i //<- address of member x shifted right by i SCALAR's
*((&x) + i) // the scalar value at that point

因此 *((&x) + i) 返回第 i 个标量。 x 代表 0,y 代表 1,z 代表 2。

关于c++ - 这个运算符重载函数返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16928422/

相关文章:

c++ - 赋值运算符何时应返回 const T &、T & 或 T?

C++ << 运算符重载和 Arduino 模板

c++ - 如何在 mbed 上的同一引脚上从 I2C 切换到 OneWire?

C++ const 语义引用

android - 使用 ndk 在 Android 上将耗时报告为 0ns

function - 来自报告函数的 SSRS 引用报告变量

c++ - 当考虑 "Inheritance"

c++ - 赋值运算符的参数类型(引用或值?)

C++ 即时启用/禁用 std::couts 的调试消息

c++ - 找不到 C++ 类中的静态 vector