How to modify a given class to use const operators

Posted by zsero on Stack Overflow See other posts from Stack Overflow or by zsero
Published on 2011-11-27T01:34:30Z Indexed on 2011/11/27 1:50 UTC
Read the original article Hit count: 312

Filed under:
|
|
|
|

I am trying to solve my question regarding using push_back in more than one level. From the comments/answers it is clear that I have to:

  1. Create a copy operator which takes a const argument
  2. Modify all my operators to const

But because this header file is given to me there is an operator what I cannot make into const. It is a simple:

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

In the given program, this operator is used to get and set data.

My problem is that because I need to have this operator in the header file, I cannot turn all the other operators to const, what means I cannot insert a copy operator.

How can I make all my operators into const, while preserving the functionality of the already written program?

Here is the full declaration of the class:

class Vector3f {

    float _item[3];

    public:

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

    Vector3f(float x, float y, float z) 
    {  _item[0] = x ; _item[1] = y ; _item[2] = z; };

    Vector3f() {};

    Vector3f & operator = ( const Vector3f& obj) 
    {
        _item[0] = obj[0];
        _item[1] = obj[1];
        _item[2] = obj[2];

        return *this;
    };

    Vector3f & operator += ( const Vector3f & obj) 
    {
        _item[0] += obj[0];
        _item[1] += obj[1];
        _item[2] += obj[2];

        return *this;
    };

    bool operator ==( const Vector3f & obj) {
        bool x = (_item[0] == obj[0]) && (_item[1] == obj[1]) && (_item[2] == obj[2]);
        return x;
    }


    // my copy operator
    Vector3f(const Vector3f& obj) {
        _item[0] += obj[0];
        _item[1] += obj[1];
        _item[2] += obj[2];

        return this;
    }

};

© Stack Overflow or respective owner

Related posts about c++

Related posts about class