具有不同const正确性的向量赋值操作符
Assignment operator on vectors with different const correctness
我有一个非常简单的方法:
void SomeClass::GetListStuff(std::vector<Stuff const *> &listStuff) const
{ listStuff = m_listStuff; }
其中m_listStuff是someeclass的成员,类型为
std::vector<Stuff *>
这段代码给了我一个错误,说
there's no match for 'operator='
in 'listStuff = ((const SomeClass*)this)->SomeClass::m_listStuff
如果我从ListStuff指针中拿走const,它会工作得很好。我也可以在listStuff上调用insert()(不改变const的正确性),它可以工作。有人能解释一下原因吗?
我认为你应该这样做:
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版本
相关文章:
- 如何从文件中为C++中的向量赋值?
- 为多维向量赋值
- C++:构造函数中的向量赋值错误
- C++标准是否对向量赋值函数或构造函数提出了明确的要求
- 两个向量赋值错误
- std::向量赋值信号 11 和信号 6
- 从两个指针对向量赋值进行段错误
- 优化向量赋值 c++
- Opencv-Mat向量赋值给一行矩阵,最快的方式
- 在C++中为向量赋值对
- 如何为结构中的向量赋值或打印值
- c++中的重载赋值操作符
- c++类继承和赋值操作符
- 带引用类成员的赋值操作符
- 复制构造函数,赋值操作符重载
- c++派生类赋值操作符
- 通过调用Move赋值操作符实现Move构造函数
- 类和向量的重载赋值操作符
- 向量赋值操作符和复制构造函数
- 具有不同const正确性的向量赋值操作符