gpt4 book ai didi

c++ - 实现纯虚函数:时出现一些错误

转载 作者:行者123 更新时间:2023-12-03 07:52:14 25 4
gpt4 key购买 nike

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。
  • 如果要实现<=运算符,只需声明它即可:-)
  • 我想您的设计目标是,如果将两个不可比较的类型传递给需要“可比较”类型的函数(例如qsort函数),则会出现编译器错误。但是,如果查看 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com