C ++没有重载运算符

时间:2014-04-13 19:47:47

标签: c++

出于某种原因,似乎跳过了自定义比较。从不打印调试字符串并且排序已关闭。

有人能发现这里的错误吗?

 bool Communication::operator<(const Communication& second) const
 {
     qDebug() << "Actually sorting";
     return (getName().compare(second.getName()) < 0);
 }

class Communication
{
public:
    bool operator<(const Communication& second) const;
    QString getName() const;
    void setName(QString nm);
    QString commName;
}

void Communication::addComm(vector<Communication*>c)
{
    // This is called for sure
    lg=c;
    std::sort ( lg.begin(), lg.end());
}

编辑: 低于我的新方法。

bool Communication::cmp(const Communication* lhs, const Communication* rhs) const
{
  return (lhs->getName().compare(rhs->getName()) < 0);
}

...error: no matching function for call to 'sort(std::vector<Communication*>::iterator, std::vector<Communication*>::iterator, <unresolved overloaded function type>)'

3 个答案:

答案 0 :(得分:8)

你的矢量包含指针:

vector<Communication*> c

但你的比较是值。您需要对指针进行比较,但这不能是operator<,因为您不能为指针重载该运算符。它应该是一个函数或函子。

bool cmp(const Communication* lhs, const Communication* rhs)
{
  return (lhs->getName().compare(rhs->getName()) < 0);
}

std::sort ( lg.begin(), lg.end(), cmp);

答案 1 :(得分:2)

运营商不会为运营商超载。如果你想根据指针上的谓词对一系列指针进行排序,你需要使用一个合适的谓词函数,例如:

 std::sort(lg.begin(), lg.end(),
     [](Communication const* c0, Communication const* c1){
         return *c0 < *c1;
     });

答案 2 :(得分:1)

您正在对vector Communication*进行排序,但您的operator<会比较const Communication&