还在苦苦敲代码开发APP?你out啦! 试试积木搭建APP吧~

passing xxx as 'this' argument of xxx discards qualifiers

来源:清泛原创     2016-10-24 17:43:30    人气:     我有话说( 0 人参与)

这是由于常量对象调用了非常量成员函数引起的错误,错误原因在于常量对象只能调用常量成员函数(因为常量成员函数约定不对非静态成员进行修改...

这是由于常量对象调用了非常量成员函数引起的错误,错误原因在于常量对象只能调用常量成员函数(因为常量成员函数约定不对非静态成员进行修改).

来自 stackoverflow的例子

#include <iostream>
#include <set>

using namespace std;

class StudentT {

public:
    int id;
    string name;
public:
    StudentT(int _id, string _name) : id(_id), name(_name) {
    }
    int getId() {    //  应该声明为const成员
        return id;
    }
    string getName() { // 应该声明为const成员
        return name;
    }
};

inline bool operator< (StudentT s1, StudentT s2) {
    return  s1.getId() < s2.getId();
}

int main() {

    set<StudentT> st;
    StudentT s1(0, "Tom");
    StudentT s2(1, "Tim");
    st.insert(s1);
    st.insert(s2);
    set<StudentT> :: iterator itr;
    for (itr = st.begin(); itr != st.end(); itr++) {
        cout << itr->getId() << " " << itr->getName() << endl;
    }
    return 0;
}

这个例子中,加入set的StudentT对象都变成const对象了,那么调用getId等方法时只能调用其const版本,因为没有定义这个版本,因此编译器提示错误.

 

解决方法就是将getId和getName方法声明为const成员,即在函数末尾加上const关键字。

const 常量成员

注:本文为本站或本站会员原创优质内容,版权属于原作者及清泛网所有,
欢迎转载,转载时须注明版权并添加来源链接,谢谢合作! (编辑:admin)
分享到: