为什么下面的cpp程序会编译出错?

bingocn 2002-10-15 07:08:16
我希望调用fun时,其中的obj不被改变。部分程序如下:

a.h中声明如下:
class otherclass
{
...
int fun(const myclass& obj);
...
};

a.cpp中实现为:
int otherclass::fun(const myclass& obj)
{
...
int num = obj.GetValueA(); (此行编译出错)
...
}

myclass类中定义的成员函数GetValueA()为
int myclass::GetValueA()
{
return ret;
}
myclass类声明为
class myclass
{
public:
int GetValueA();

private:
int ret;
};


在Linux下编译:
g++ -c -Wall a.cpp
错误信息为:
passing `const myclass' as `this' argument of `int
myclass::GetValueA ()' discards qualifiers

但将a.h,a.cpp中相应的const去掉,则编译通过。
...全文
58 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
bingocn 2002-10-15
  • 打赏
  • 举报
回复
谢谢,现在可以了 :)
hehe214 2002-10-15
  • 打赏
  • 举报
回复
拿回去研究一下
bingocn 2002-10-15
  • 打赏
  • 举报
回复
谢谢,现在可以了 :)
wintersun 2002-10-15
  • 打赏
  • 举报
回复
需要知道,const对象obj只能调用const成员函数,而GetValueA()却不是const成员函数;你可以将GetValueA()申明为const;也可以在fun()中用const_cast将obj的const属性去掉;也可以用你自己上面提到的方法。当然,第一种方法最好,你没有理由不那么做。

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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