问题一个const作函数参数的问题。

zhoufanking 2008-09-09 03:22:46
出问题的函数如下:
vector<int> *buildVec(const Sequence &sq)
{
vector<int> *newSeq = new vector<int>;
int sqSize = sq.getSeqSize();
int elem;

for(int id = 1; id <= sqSize; id++)
{
elem = sq.getElemByIndex(id);
newSeq->push_back(elem);
}
return newSeq;
}
编译后提示:
error: passing `const Sequence' as `this' argument of `int Sequence::getElemByIndex(int)' discards qualifiers

如果去掉形参中的const的话就正常了,为什么呢?我并没有修改sq的值啊?
付getElemByIndex的定义:
int Sequence::getElemByIndex(int index)
{
int liId = index;

if( isIndexOk(liId) )
return Seq[index-1];
else
{
cerr << "Bad index found!" << endl;
return -1;
}
}
...全文
129 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhoufanking 2008-09-09
  • 打赏
  • 举报
回复
搞忘了,const对象只能访问const成员函数!
谢大家!
yuwei2589 2008-09-09
  • 打赏
  • 举报
回复
int Sequence::getElemByIndex(int index) const;加上const


vector <int> *buildVec(const Sequence &sq);或者去掉const!
zclever 2008-09-09
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 xkyx_cn 的回复:]
const对象只能调用const成员函数
非const对象能调用const和非const成员函数
[/Quote]
非const对象优先调用非const成员函数
e_sharp 2008-09-09
  • 打赏
  • 举报
回复
const对象只能调用const成员函数
ekschencn 2008-09-09
  • 打赏
  • 举报
回复
在你的代码两处有调用sq的方法的,一个是getSeqSize, 另一个是getElemByIndex。
我猜你上面的那两个方法没有声明为const的吧。声明为const以后,就是保证了这个方法调用不会引起成员对象的改变的;不加这个关键字,一律会被认为是可能改变的,不过你实际的代码如何。


int Sequence::getElemByIndex(int index) const
{
int liId = index;
...

这样就好了,当然,getSeqSize也需要这样。
xkyx_cn 2008-09-09
  • 打赏
  • 举报
回复
const对象只能调用const成员函数
非const对象能调用const和非const成员函数
帅得不敢出门 2008-09-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 tjianli 的回复:]
常量成员是禁止调用非常量成员函数,防止发生改变
非常量成员可以调用常量成员函数
[/Quote]
应该是常量对象
jay的Fans 2008-09-09
  • 打赏
  • 举报
回复
常量成员是禁止调用非常量成员函数,防止发生改变
非常量成员可以调用常量成员函数

64,675

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧