Cannot convert 'this' pointer from 'const Line' to 'Line &' explanation?

后端 未结 3 979
南方客
南方客 2021-01-30 12:54

This method:

bool Point::Intersects(const Line& line) const {
    return (line.ContainsPoint(*this, false));
}

causes this error: cannot co

3条回答
  •  一整个雨季
    2021-01-30 13:36

    The problem is in fact a simple one:

    you have a class A, with a non-const method foo(), you are invoking non-const method foo() through a ref to const A.

    const A& a = ...;
    a.foo();  // failed
    

    That's what const aimed for: a const variable means, it is declared not going to be changed. While foo() "is going to change itself" (as foo() is a non-const method, which means: "I am legal to change thing inside"), that's why compiler complains: you have a const var (a), but you are going to change its content (thru foo())

    The way to solve is straight forward, but you should know which way is correct to do:

    1) If you are sure that foo() should be legal to be invoked through const ref etc, you should declare it as a const method: A::foo() const {...}

    2) If you know that foo() is not appropriate to make const, you should consider

    2.1) review "a" to see if it is more appropriate to make non-const, or

    2.2) find another const method in A that did the work.

    (There are some other way like using mutable, or const_cast, but that's not the way to go for 99.9% of time. So I didn't mention here)

提交回复
热议问题