找不到运算符<对于指针类型

Could not find operator< for pointer type

本文关键字:指针 类型 于指针 运算符 lt 找不到      更新时间:2023-10-16

我正在尝试使用插入排序订购指针的向量,并带有超载&lt;操作员(无法使用任何库)。拥有一个包含另一个的课程,类似于:

class A {   
 vector<B*> v;
 void order();
}
class B {
int id;                         //each one is unique
virtual double num() {} const;
bool operator<(const B* b2) const;
}
class B1: public B {
double num() {} const;
}
class B2: public B {
double num() {} const;
}

每个孩子都有不同的计算NUM的方式,并且使用NUM作为第一个标准的Double返回的Double进行排序,然后再进行ID。(对不起,缩进)

void A::order() {
for (unsigned int p = 1; p < v.size(); p++)    
{
    ClassB* tmp = v[p];
    int j;
    for (j = p; j > 0 && tmp < v[j-1]; j--) // Error on this line
        v[j] = v[j-1];
    v[j] = tmp;     
}
}

bool B::operator<(const B* b2) const {
cout << "Operator <n";
if(this->num()!=b2->num())
    return this->num()<b2->num();
return id<d2->id;
}

我不明白为什么在尝试比较两个指针时未调用操作员。

此操作员

bool operator<(const B* b2) const;

允许您将LHS上的B与RHS上的B*进行比较。您正在尝试与两侧的B*进行比较,因此操作员不应用。

您不能超载指针比较运算符,因此可以用B(或const B&)进行比较,并在比较时删除指针:

for (j = p; j > 0 && *tmp < *v[j-1]; j--)

您不能超载操作员比较指针。即使可以的话,大多数时候仍然是非法的。您只能比较指向同一数组内的内存或数组结束后一个位置的指向。除此之外,其他任何是不确定的行为。

您的B::bool operator<(const B* b2) const;实际上应该是bool operator<(const B& b2) const;。这使您可以比较2个 B对象,而不是对象和指向对象的指针 - 这是您的代码现在所做的

如果您必须对指针容器进行排序,则可以提供一个比较 function 作为回调,以将2个指针作为参数,但将operator<作为具有指针的成员实现感官。

相关文章: