原代码
class TestOverloadLessThan
{
public:
TestOverloadLessThan( int m ) : m_int(m){};
int getInt(){ return m_int;};
bool operator<( const TestOverloadLessThan& t) const
{
return ( this->getInt() < t.getInt() );
};
private:
int m_int;
};
//bool operator<( const TestOverloadLessThan& t1,const TestOverloadLessThan& t2)
//{
// return ( t1.getInt() < t2.getInt() );
//}
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
list<TestOverloadLessThan> l;
for ( int n=0 ; n<10 ; ++n )
{
TestOverloadLessThan t(n);
l.push_front(t);
}
l.sort();
for ( list<TestOverloadLessThan>::const_iterator it=l.begin() ; it!=l.end() ; ++it )
{
cout<<(*it).getInt()<<endl;
}
system("pause");
return 0;
}
无论成员函数与非成员函数都是这个错误。两个const和const_iterator:
error C2662: 'TestOverloadLessThan::getInt' : cannot convert 'this' pointer from 'const TestOverloadLessThan' to 'TestOverloadLessThan &'
把所有的const去掉之后就可以通过,加上默认构造函数加上const可以通过
class TestOverloadLessThan
{
public:
TestOverloadLessThan(){};
TestOverloadLessThan( int m ) : m_int(m){};
int getInt(){ return m_int;};
bool operator<( const TestOverloadLessThan& t) const
{
return ( this->getInt() < t.getInt() );
};
private:
int m_int;
};
测试代码与原来一样。
请问这里是在哪里影响了this指针转换const——>普通引用的