class Comparable
{
public:
virtual bool compare(Comparable* c) = 0;
};
class FreightTrainRoute :public Comparable
{
protected:
int nbOfWagons;
float* weigthPerWagon;
public:
//错误在这里:'bool Comparable::compare(Comparable *)':无法转换参数1从“可比较”到“可比较*”
virtual bool compare(Comparable* c)
{
FreightTrainRoute* t = (FreightTrainRoute*)c;
if (this->totalWeight() < t->totalWeight());
{
return -1;
}
}
//老实说,我什至不知道在比较中如何或在何处使用运算符<功能
bool operator<(const FreightTrainRoute& f1, const FreightTrainRoute& f2)
{
/*if (f2.weigthPerWagon < f2.weigthPerWagon)
{
return -1;
}
else if (f2.weigthPerWagon == f2.weigthPerWagon)
{
return true;
}
else
{
return false;
}*/
}
您能帮我摆脱这些错误吗?
最佳答案
您的代码中存在几个问题:
virtual bool compare(Comparable* c1, Comparable* c2)
,您强加了FreightTrainRoute
来实现具有完全相同签名的compare
方法,而您想强加virtual bool compare(FreightTrainRoute* c1, FreightTrainRoute* c2)
。 c1
优先于c2
,比较函数将返回实数负数;如果c2
优先于c1
,则比较函数将返回正数;如果根据基础顺序等效,则返回0。 <=
运算符,只需声明它即可:-) std::qsort
implementation,您会发现订单关系是一个回调参数。如果考虑整数列表,则可以通过升序或降序对元素进行排序。如果考虑对象列表,则可以根据任何基于属性的顺序对元素进行排序。总而言之,在这样的函数中“硬编码”“比较”顺序不是一个好主意。 #include <iostream>
#include <vector>
#include <numeric>
class FreightTrainRoute {
std::vector<float> weightPerWagon;
public:
FreightTrainRoute(const std::vector<float> & weightPerWagon):
weightPerWagon(weightPerWagon)
{}
inline float totalWeight() const {
return std::accumulate(
weightPerWagon.begin(),
weightPerWagon.end(),
0
);
}
};
inline bool operator <= (
const FreightTrainRoute & f1,
const FreightTrainRoute & f2
) {
return f1.totalWeight() <= f2.totalWeight();
}
inline float compare(
const FreightTrainRoute * f1,
const FreightTrainRoute * f2
) {
return f1->totalWeight() - f2->totalWeight();
}
int main() {
using namespace std;
vector<float>
w1 = {1.0, 2.0, 3.0},
w2 = {10.0, 20.0};
FreightTrainRoute f1(w1);
FreightTrainRoute f2(w2);
if (f1 <= f2) {
cout << "f2 is heavier than f1" << endl;
} else {
cout << "f1 is heavier than f2" << endl;
}
cout << "compare(f1, f2) = " << compare(&f1, &f2) << endl;
return 0;
}
结果:f2 is heavier than f1
compare(f1, f2) = -24
关于c++ - 实现纯虚函数:时出现一些错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65393549/