0

I'm trying to learn about linear algebra through a book and the author leaves a code block for a basic struct for Vector3D. I understand everything except for the two blocks with float& operator and const float& operator. Is it possible if I could get an in depth explanation of the code here?

I've attempted to google the usage of operators which makes those two blocks of code seem like some sort of implicit conversion is happening, but I'm still at a loss for everything else.

#include <iostream>
using namespace std;

//Math Engine

struct Vector3D
{
    float x, y, z;

    Vector3D(float X, float Y, float Z)
    {
        x = X;
        y = Y;
        z = Z;
    }

    Vector3D() = default;

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

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

int main()
{
    return 0;
}
  • 4
    What, **exactly**, you don't understand? Did you learn C++ from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? Currently, it seems, that those `operator[]`s, invoke undefined behavior, for any `i != 0`. – Algirdas Preidžius Oct 28 '19 at 17:56
  • see [Can modern AI be used to program impressive graphics effects on very low performance home-retrocomputers, in particular 'A 3D-rotating-cube'](https://retrocomputing.stackexchange.com/a/6055/6868) and look at the `template class _vec2` its handling the problem described in previous comment ... – Spektre Oct 29 '19 at 21:12
  • This code makes no sense. x is a float, not an array. – duffymo Sep 29 '21 at 13:43

1 Answers1

0
#include <iostream>
using namespace std;

//Math Engine

struct Vector3D
{
    //take array instead of separate elements, this it will be contiguous in memory
    float x[3];

    Vector3D(float X, float Y, float Z)
    {
        x[0] = X;
        x[1] = Y;
        x[2] = Z;
    }

    Vector3D() = default;
    
    //this will allow to Get and Set the value of vector
    float& operator [](int i)
    {
        assert( 0 <= i && i < 3 );
        return x[i];
    }

    //this will **NOT** allow to Set the value of vector but you can get it
    const float& operator [](int i) const
    {
        assert( 0 <= i && i < 3 );
        return x[i];
    }
};

int main()
{
    return 0;
}