我有一个类Foo
这是一个 self 引用的树状结构(最低限度):
class Foo {
public:
// Gets this child's position relative to it's parent.
int getPosition() const {
return parent->indexOf(this);
}
int indexOf(const Foo *const child) const {
return children.indexOf(child); // this line causes an error.
}
private:
Foo *parent;
QList<Foo *> children;
}
行return children.indexOf(child)
期待 const T &value
根据 QList docs 通过, 这解析为 Foo *const &value
对于我的场景。
为了我的getPosition()
调用我自己的方法 indexOf()
方法需要签名 const Foo *child
至少为了通过 this
来自 const 方法。 (因为这是 const Foo *const
)。
我的代码不会编译为 const Foo *const child
无法转换为 Foo *const child
对于 QList::indexOf
.我的两种方法都没有修改对象状态,因此它们应该是 const(即我不想取消成本 getPosition
来接收非常量 this
)。
所以问题是,我如何从 this
开始?在 const 上下文中 ( const Foo *const
) 到什么 QList::indexOf
需要。我应该 const 类型转换 this
里面getPosition
因为我知道我的 indexOf
(以及随后的调用)不会改变它?
还有什么我应该做的吗?也许我的设计有问题。
最佳答案
我认为这是 const_cast
的一个完全合理的用例,但是它不是 this
您需要 const_cast
,而是 child
。在这种情况下,QList::indexOf
需要一个指向 Foo
(Foo* const
) 的常量指针,但是 child
是指向常量 Foo
(const Foo* const
) 的常量指针。没有从 Foo* const
到 const Foo* const
的隐式转换,因为这会从指向的值中删除常量。
因此,为了修复您的代码,我会将行更改为
return children.indexOf(const_cast<Foo*>(child));
你知道 QList::indexOf
不会修改 child
指向的任何内容,因此这不会产生未定义的行为。然而,我会添加一条评论来解释为什么 const_cast
是必要的。
关于c++ - 当一个方法只接受 Foo *const 时,我应该 const_cast "this"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17156558/