C ++ () overload operator in structure

Here is the code from b2Math.h from the Box2d physics engine.

struct b2Vec2
{   ...
    /// Read from and indexed element.
    float operator () (int i) const
    {
         return (&x)[i];
    }
    /// Write to an indexed element.
    float operator () (int i)
    {
         return (&x)[i];
    }
    ...
    float x, y;
}

Why can't we use SomeVector.x and SomeVector.y to read / write vector coordinates? How does the line work return (&x)[i];? I mean that massive marriages [] after referencing the x component of the structure are not clear to me.

Thanks in advance for your reply.

+4
source share
1 answer

Here is the code from b2Math.h from the Box2d physics engine.

An error message appears in the copy and paste of the Box2D source code. In particular, the missing ampersand in the non-constant method is apparently missing.

In addition, this code fragment appears from a code base different from the current released code 2.3.2.

Box2D 2.3.2 GitHub:

/// Read from and indexed element.
float32 operator () (int32 i) const
{
    return (&x)[i];
}

/// Write to an indexed element.
float32& operator () (int32 i)
{
    return (&x)[i];
}

SomeVector.x SomeVector.y / ?

, .

Box2D (b2AABB::RayCast), , -, ( b2AABB::RayCast, " , p179" ), x y . , ( Box2D) : (a) , (b) (c) . , .

Box2D, . [] ( ()) switch x y. , , , undefined w.r.t. ++.

, (, , , , , , , ):

/// Accesses element by index.
/// @param i Index (0 for x, 1 for y).
auto operator[] (size_type i) const
{
    assert(i < max_size());
    switch (i)
    {
        case 0: return x;
        case 1: return y;
        default: break;
    }
    return x;
}

/// Accesses element by index.
/// @param i Index (0 for x, 1 for y).
auto& operator[] (size_type i)
{
    assert(i < max_size());
    switch (i)
    {
        case 0: return x;
        case 1: return y;
        default: break;
    }
    return x;
}

(& x) [i]; ?

, .

, x y- , ; . , (&) x, , i.

, , , ++. .

, .

0

Source: https://habr.com/ru/post/1674774/


All Articles