请教:关于类中的mutable数据成员

wengchaohui 2008-04-28 02:37:38
我在书本上看到一个例子,
int getcurrent();
class a
{public:
bool s()const;

private:
mutable int y;
};
bool a::s()const
{y=getcurrent();
return 0;
}
如上,一切正常,可是为什么将上面改为
class a
{public:
bool s()const;
int getcurrent();
private:
mutable int y;
};
bool a::s()const
{y=getcurrent();
return 0;
}
就不行了(就是把int getcurrent();从类外面改为类里面,)提示的错误信息是这样的
: error C2662: 'getcurrent' : cannot convert 'this' pointer from 'const class a' to 'class a &'
再一次麻烦各位了,,,
...全文
82 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
baihacker 2008-04-28
  • 打赏
  • 举报
回复
int getcurrent();
class a
{public:
bool s()const;

private:
mutable int y;
};
bool a::s()const
{y=getcurrent();
return 0;
}
这里getcurrent()是外部函数,在类里面调用,没有问题
class a
{public:
bool s()const;
int getcurrent();
private:
mutable int y;
};
bool a::s()const
{y=getcurrent();
return 0;
}
在这里getcurrent是类内部的普通成员函数,而a::s是常函数,常函数是说,内部成员不能被改变,而在常函数内部调用一个普通成员函数,那么内部成员就有可能改变,所以常函数内部不能调用普通成员函数,于是就错了.
在语法上是常函数使用的是是const a* const this普通函数使用的是a*const this.
taodm 2008-04-28
  • 打赏
  • 举报
回复
找本C++ Primer,书后索引表里查查mutable。
baihacker 2008-04-28
  • 打赏
  • 举报
回复
int getcurrent() const;
就能通过

64,664

社区成员

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

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