简体   繁体   English

需要帮助理解这个基本的 Vector3D 结构的代码

[英]Need help understanding this basic Vector3D structure's code

I'm trying to learn about linear algebra through a book and the author leaves a code block for a basic struct for Vector3D.我正在尝试通过一本书学习线性代数,作者为 Vector3D 的基本结构留下了一个代码块。 I understand everything except for the two blocks with float& operator and const float& operator.除了带有 float& 运算符和 const float& 运算符的两个块外,我什么都懂。 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;
}
#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM