具有不同const正确性的向量上的赋值运算符

时间:2013-01-05 05:13:25

标签: c++ stl

我有一个非常简单的方法:

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

如果我将const从ListStuff指针中取出,它的工作正常。我也可以在listStuff上调用insert()(不改变const的正确性)并且它可以工作。谁能解释为什么?

1 个答案:

答案 0 :(得分:1)

我认为你应该这样做:

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()
}

自己编写非const版本。

相关问题