找不到运算符<对于指针类型
Could not find operator< for pointer type
我正在尝试使用插入排序订购指针的向量,并带有超载&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<
作为具有指针的成员实现感官。
相关文章:
- C++中的双指针类型转换
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 将类指针类型转换为键时出错
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- C++在一个映射中存储不同的指针类型(并处理销毁)
- 指针类型类成员的动态强制转换的恒定性是什么?
- 我正在尝试将表的地址传递给要在另一个函数中使用的指针,但得到不兼容的指针类型
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- STL 函数和函数类型与函数指针类型
- 如何调用指针类型的方法(禁用多态性)?
- 为什么新表达式可以正确生成指针类型,即使它应该返回 void*?
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 是否允许调用方对我的 Builder 类使用任何指针类型(包括智能指针)?
- OPENCL 警告:不兼容的指针类型将'float __global[16]'传递给类型为 '__global float4 的参数 *
- 专门用于"direct"函数类型(与函数指针类型相对)
- 指向成员的指针类型和模板
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 在C++17中,为什么类模板和函数模板的指针类型推导明显不一致
- 为什么允许将整型、枚举和指向成员的指针类型reinterpret_cast到自身?