C2662 Cannot convert "this" pointer from const student "to" student & "
Operating environment:
vc2010 learning version
example:
#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;
}
The error is reported as follows:
error C2662: "student :: getAge": Cannot convert "this" pointer from "const student" to "student &"
Reason:
it is const and getAge is not const, because it is constant, but it may be wrong if it involves changes
Solution:
Modify:
int getAge() const
{
return age;
}
Running results:
18 19