Passing a const object by reference.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Guest's Avatar

    #1

    Passing a const object by reference.

    Hey all.

    I just changed from this:

    mat4& operator = (mat4 & mymat4);

    to this:

    mat4& operator = (mat4 const& mymat4);

    all over my different classes, as some compilers compiled without the const, but I learned that it is necessary.

    Now, I get this error:

    binary '[' : no operator found which takes a left-hand operand of type 'const mat4' (or there is no acceptable conversion)

    Here is the function implementation:

    mat4& mat4::operator = (mat4 const& mymat4)
    {
    m[0] = mymat4[0]; m[4] = mymat4[4]; m[8] = mymat4[8]; m[12] = mymat4[12];
    m[1] = mymat4[1]; m[5] = mymat4[5]; m[9] = mymat4[9]; m[13] = mymat4[13];
    m[2] = mymat4[2]; m[6] = mymat4[6]; m[10] = mymat4[10]; m[14] = mymat4[14];
    m[3] = mymat4[3]; m[7] = mymat4[7]; m[11] = mymat4[11]; m[15] = mymat4[15];
    return *this;
    }

    And here is the definition of the [] operator:

    float& mat4::operator [] (int subscript)
    {
    return m[subscript];
    }

    Anyone understand this error?


    Thanks!



  • Pete C

    #2
    Re: Passing a const object by reference.

    <dontspam@_dyla n_.gov> wrote:[color=blue]
    > And here is the definition of the [] operator:
    > float& mat4::operator [] (int subscript)
    > {
    > return m[subscript];
    > }[/color]

    You need to define another operator[], but const - like this:

    const float& mat4::operator [] (int subscript) const
    {
    return m[subscript];
    }

    This version of the function will be called by the (const)
    right-hand-side of all your assignments.
    This may or may not compile - I don't know, because you haven't told us
    the type of the 'm' member variable. But give it a try.

    Comment

    Working...