首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不同常量正确性向量上的赋值算子

不同常量正确性向量上的赋值算子
EN

Stack Overflow用户
提问于 2013-01-05 13:13:25
回答 1查看 69关注 0票数 1

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

代码语言:javascript
运行
复制
void SomeClass::GetListStuff(std::vector<Stuff const *> &listStuff) const
{   listStuff = m_listStuff;   }

其中,m_listStuff是SomeClass的成员,类型为

代码语言:javascript
运行
复制
std::vector<Stuff *> 

这段代码给出了一个错误:

代码语言:javascript
运行
复制
there's no match for 'operator='
in 'listStuff = ((const SomeClass*)this)->SomeClass::m_listStuff

如果我从ListStuff指针中去掉const,它就能正常工作。我也可以在listStuff上调用insert() (不改变常量的正确性),并且它可以工作。有谁能解释一下原因吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-05 13:21:47

我认为你应该这样做:

代码语言:javascript
运行
复制
void SomeClass::GetListStuff(std::vector<Stuff*> &listStuff) const
{   
       listStuff = m_listStuff;   
}

也就是说,使用std::vector<Stuff*>而不是std::vector<Stuff const*>,因为我怀疑m_listStuff被声明为std::vector<Stuff*>。所以参数类型应该与之匹配。

我认为更好的方法是:

代码语言:javascript
运行
复制
std::vector<Stuff*> SomeClass::GetListStuff() const
{   
       return m_listStuff; //return a copy!
}

或者更好的方法是公开迭代器:

代码语言:javascript
运行
复制
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()
}

自己编写非常量版本。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14168854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档