jeudi 27 mai 2021

C++ read and write information with [] overload

I have the following class :

class MyPoint
{
    public:
    
        // Constructor
        MyPoint(double, double, double);

        // Destructor
        virtual ~MyPoint(){};

    protected:

    private:
        double x;
        double y;
        double z;

};

I would like to overload the operator [] to read and write data.

Something like:

myPoint[0] will return x
myPoint[1] will return y
myPoint[2] will return z

And if I do:

myPoint[0]=2 will set x = 2
myPoint[1]=3 will set y = 3
myPoint[z]=4 will set z = 4

For the first part I have:

double operator[](int entry)
{
    if (entry==0)
        return x;
    else if(entry==1)
        return y;
    else if(entry==2)
        return z;
}

For the second I do not know.

Aucun commentaire:

Enregistrer un commentaire