LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 838|回复: 1

const成员函数和非const成员函数作链式表达时出错

[复制链接]
发表于 2005-12-5 16:20:42 | 显示全部楼层 |阅读模式
以下源代码编译报错:

passing `const A' as `this' argument of `const int&
   A::getInt()' discards qualifiers



  1. #include <iostream>

  2. class A
  3. {
  4.     public:
  5.         A() : member(5) {}
  6.         const int& getInt() {
  7.             return member;
  8.         }
  9.     private:
  10.         int member;
  11. };

  12. class B
  13. {
  14.     public:
  15.         const A & getA() const {
  16.             return a;
  17.         }
  18.     private:
  19.         A a;
  20. };

  21. int main()
  22. {
  23.     using namespace std;
  24.     B b;
  25.     b.getA().getInt();
  26. }
复制代码


如果A::getInt声明成 const int & getInt() const;就没问题。

如果我要用以上的两个class,而不修改它源码,应该怎么做呢?
发表于 2005-12-5 18:54:39 | 显示全部楼层
[PHP]
int main()
{
    using namespace std;
    B b;
    A a;
    a = b.getA();
    a.getInt();
}
[/PHP]
因为B::getA()返回是一个const 类型的对象引用,所以只能调用const函数。
要想不修代码而使用它,只能复制一个和它一样的非const对象,
然后再调用非const成员函数。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表