无法将“this”指针从“const Line”转换为“Line&'说明? [英] Cannot convert 'this' pointer from 'const Line' to 'Line &' explanation?

查看:476
本文介绍了无法将“this”指针从“const Line”转换为“Line&'说明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此方法:

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

导致此错误:无法将'this'指针从'const Line' 'Line&'
此更改:

causes this error: cannot convert 'this' pointer from 'const Line' to 'Line &' This change:

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

修复错误,但似乎不是正确的方法来解决问题。为什么原来的方法被认为是错误?

fixes the error, but doesn't seem the right way to fix the issue. Why is the original method considered an error?

如果它有帮助, ContainsPoint(const Point& point,bool isInfinite)

推荐答案

你自己提供的答案,

Intersects 方法中,参数被声明为 const 。这限制了如何使用此变量。具体来说,你只能调用 const 方法,你只能将它传递给需要 const 的对象。

In your Intersects method, the parameter line is declared const. This restricts how you can use this variable. Specifically, you can only call const methods on it, and you can only pass it to methods expecting a const Line object.

但是,您指出 ContainsPoint 未声明 const 。因此,它不满足上述要求(即,不允许在 const 对象上调用非< - code> const )。这是为什么原来的方法生成错误,它也解释了为什么你的第二版本工作,因为限制通过 const_cast 减轻。

However, you pointed out that ContainsPoint is not declared const. So it does not satisfy the requirement mention above (i.e. calling a non-const method on a const object is not allowed). This is why the original method generates the error, and it also explains why your second version works, since the restriction is alleviated via the const_cast.

真正的问题在于 ContainsPoint 的声明(也可能是它调用的任何方法,因为它们也是非常量的)。这里似乎有一个大的设计缺陷。因为 ContainsPoint 的目的是检查 Point 是否在 / code>副作用将是意想不到的。所以应该没有理由不是一个const方法。事实上(你的例子显示这个), Line 的用户会期望 ContainsPoint const 方法。因此,真正的解决方案是改变 Line 类的设计,使得 ContainsPoint 的方法声明为 const ,并且只有清楚地改变实例状态的方法是非 - const

The real problem is in the declaration of ContainsPoint (and probably also with whatever methods it calls, as they are also non-const). There appears to be a large design flaw here. Since the purpose of ContainsPoint is to check whether or not a Point is on a Line side-effects will be unexpected. So there should be no reason for it to not be a const method. In fact (and your example show this), users of Line would expect ContainsPoint to be a const method. Therefore, the real solution is to change the design of the Line class so that methods like ContainsPoint are declared const, and only methods which clearly change the state of an instance are left non-const

这篇关于无法将“this”指针从“const Line”转换为“Line&amp;'说明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆