我有一个非常简单的方法:
void SomeClass::GetListStuff(std::vector<Stuff const *> &listStuff) const
{ listStuff = m_listStuff; }其中,m_listStuff是SomeClass的成员,类型为
std::vector<Stuff *> 这段代码给出了一个错误:
there's no match for 'operator='
in 'listStuff = ((const SomeClass*)this)->SomeClass::m_listStuff如果我从ListStuff指针中去掉const,它就能正常工作。我也可以在listStuff上调用insert() (不改变常量的正确性),并且它可以工作。有谁能解释一下原因吗?
发布于 2013-01-05 13:21:47
我认为你应该这样做:
void SomeClass::GetListStuff(std::vector<Stuff*> &listStuff) const
{
listStuff = m_listStuff;
}也就是说,使用std::vector<Stuff*>而不是std::vector<Stuff const*>,因为我怀疑m_listStuff被声明为std::vector<Stuff*>。所以参数类型应该与之匹配。
我认为更好的方法是:
std::vector<Stuff*> SomeClass::GetListStuff() const
{
return m_listStuff; //return a copy!
}或者更好的方法是公开迭代器:
std::vector<Stuff*>::const_iterator cbegin() const
{
return m_listStuff.cbegin(); //return const_iterator (C++11 only)
//in C++03, you can use begin()
//it will work same as cbegin()
}
std::vector<Stuff*>::const_iterator cend() const
{
return m_listStuff.cend(); //return const_iterator (C++11 only)
//in C++03, you can use end()
//it will work same as cend()
}自己编写非常量版本。
https://stackoverflow.com/questions/14168854
复制相似问题