Skysilence 2013-05-29 14:15 采纳率: 0%
浏览 2008

C++中操作符重载的const与默认构造函数

原代码

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——>普通引用的

  • 写回答

1条回答 默认 最新

  • 码界一棵葱 2016-08-19 02:49
    关注

    请问你的问题解决了么,我碰到和你一样的问题!

    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型