C2662 不能将"this"指针从const student" 转换为"student &"
运行环境:
vc2010学习版
例子:
#include <iostream>
#include <set>
#include <functional>
#include <algorithm>
using namespace std;
class student
{
public:
student(int age)
{
this->age = age;
}
bool operator < (const student &right) const
{
return this->age < right.age;
}
int getAge()
{
return age;
}
private:
int age;
};
int main()
{
set<student> setStu; //等同于 set<student, less<student>>
setStu.insert(student(18));
setStu.insert(student(19));
for(set<student>::iterator it = setStu.begin(); it != setStu.end(); it++)
{
cout<<it->getAge();
cout<<" ";
}
cout<<endl;
system("pause");
return 0;
}
报错如下:
error C2662: “student::getAge”: 不能将“this”指针从“const student”转换为“student &”
原因:
it 它是const 而 getAge 不是const, 因为 it 是常量一但涉及可能改变就会报错
解决方案:
修改:
int getAge() const
{
return age;
}
运行结果:
18 19