指针是否存储在 std::set const 中
Are pointers stored in std::set const?
我正在寻找代码中的错误,但我有一个问题:
class a
{
public:
void foo(int a) {}
}
std::set<a*> set;
std::set<a*>::iterator it = set.begin();
it->foo(55); //gives me error:
// error: request for member ‘foo’ in ‘* it.std::_Rb_tree_const_iterator<_Tp>::operator-><a*>()’, which is of pointer type ‘a* const’ (maybe you meant to use ‘->’ ?)
为什么它不允许我在上面使用非常量函数?在不使用强制转换的情况下,我该怎么做才能拥有一组非常量指针?
您需要取消引用两次:
(*it)->foo(55);
– it
是指向指针的迭代器。如果您有std::set<a>
而不是std::set<a*>
,您的代码是正确的。
问题是您需要先尊重迭代器,然后再尊重指针。 将it->foo(55);
替换为(*it)->foo(55);
这将起作用。
你是间接的一级。
(*it)->foo(55);
有效,因为it
实际上是指向存储类型的指针,而存储类型本身就是一个指针。