作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
class Comparable
{
public:
virtual bool compare(Comparable* c) = 0;
};
class FreightTrainRoute :public Comparable
{
protected:
int nbOfWagons;
float* weigthPerWagon;
public:
//错误在这里:'bool Comparable::compare(Comparable *)':无法转换
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/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!