const造成的一些错误记录

来源:互联网 发布:瑞士胡椒盐包带淘宝 编辑:程序博客网 时间:2024/05/16 07:49
  1. 重载”=”号操作符出现时出现no known conversion for argument 1 from 'CBinmap' to 'CBinmap&'

    错误代码

    Class CBinmap{    CBinmap& operator=(CBinmap &bmap);}CBinmap& CBinmap::operator=(CBinmap &bmap){    if(this==&bmap) return *this;//avoid copy itself    ...    ...    return *this;}

    然后在使用中如下调用出错

        CBinmap w(20,20,50),y(20,20,100);    CBinmap z=y;    z=y-w;
    ../../PZJBY11/main.cpp:18:6: error: no match for 'operator=' (operand types are 'CBinmap' and 'CBinmap')     z=y-w+y;      ^......../../PZJBY11/CBinmap.h:247:14: note: CBinmap& CBinmap::operator=(CBinmap&)     CBinmap& operator=(CBinmap &bmap);              ^../../PZJBY11/CBinmap.h:247:14: note:   no known conversion for argument 1 from 'CBinmap' to 'CBinmap&'

    解决方法,需要添加const修饰。

        Class CBinmap{        CBinmap& operator=(const CBinmap &bmap);    }    CBinmap& CBinmap::operator=(const CBinmap &bmap){        if(this==&bmap) return *this;//avoid copy itself        ...        ...        return *this;    }

    原因:因为y-w返回的是一个临时的CBinmap对象,C++中不允许将一个临时变量转换成non-const reference,所以错误。
    参见问答
    再者,注意 CBinmap z=y;中初始化调用的是构造函数,不是=赋值函数。

  2. Error: passing ‘const xxx’ as ‘this’ argument of ‘xxx’ discards qualifiers

    错误代码

    class CBinmap{    CBinmap::CBinmap(const CBinmap &bmap){        clearValue();        bmap.piccopy(this);    }    int CBinmap::piccopy(CBinmap *lpDespic){        ...        ...        return 0;    }}

    错误信息:

    /opt/mnt/rootfs/home/fa/Documents/PZJBY11/CBinmap.cpp:9: error: passing 'const CBinmap' as 'this' argument of 'int CBinmap::piccopy(CBinmap*)' discards qualifiers [-fpermissive]     bmap.piccopy(this);                      ^

    解决方法:

            int CBinmap::piccopy(CBinmap *lpDespic) const{            ...            ...            return 0;        }

    原因:因为CBinmap::CBinmap(const CBinmap &bmap)中传入的bmap参数是const类型,所以其调用的方法也必须是const的才行(既然bmap在构造中是一个不能更改的类型,那如果它的方法不是const的,则不能保证在此方法中有更改数据的行为,这逻辑上就不通了,所以C++报错),即const 对象只能调用const的方法。
    同时注意下:类的成员函数后面加上const修饰,表明该成员函数不能修改类中任何非const成员。

关于const的总结参见–关于C++ const 的全面总结,其中的建议不错:

四、使用const的一些建议

  • 要大胆的使用const,这将给你带来无尽的益处,但前提是你必须搞清楚原委;
  • 要避免最一般的赋值操作错误,如将const变量赋值,具体可见思考题;
  • 在参数中使用const应该使用引用或指针,而不是一般的对象实例,原因同上;
  • const在成员函数中的三种用法(参数、返回值、函数)要很好的使用;
  • 不要轻易的将函数的返回值类型定为const; ·
  • 除了重载操作符外一般不要将返回值类型定为对某个对象的const引用;
  • 任何不会修改数据成员的函数都应该声明为const 类型。
原创粉丝点击