gpt4 book ai didi

c++ - 具有不同 const 正确性的 vector 的赋值运算符

转载 作者:太空宇宙 更新时间:2023-11-04 12:00:51 24 4
gpt4 key购买 nike

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

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 正确性)并且它有效。谁能解释一下为什么?

最佳答案

我认为你应该这样做:

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

自己编写非常量版本。

关于c++ - 具有不同 const 正确性的 vector 的赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14168854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com