C ++类运算符重载不适用于std :: sort

时间:2019-05-16 05:35:28

标签: c++ sorting operator-overloading operators std

因此,我一直在尝试构建一个中位数生成器,该中位数生成器采用分数并生成中位数,但是似乎当前我无法对自己定义的RationalNumber类的向量进行排序。我已经重载了许多运算符(* + / ==等),但是当在其他地方内联调用时,它们似乎不起作用。

RationalNumber RationalNumber::operator*(const RationalNumber& r)
{
    RationalNumber result(numerator * r.numerator, denominator * r.denominator);
    result.reduceFraction();
    return result;
}   

RationalNumber RationalNumber::operator*(int x)
{
    RationalNumber result(numerator * x, denominator);
    result.reduceFraction();
    return result;
}

RationalNumber RationalNumber::operator/(const RationalNumber& r)
{
    RationalNumber result(numerator * r.denominator, denominator * r.numerator);
    result.reduceFraction();
    return result;
}

RationalNumber RationalNumber::operator/(int x)
{
    RationalNumber result(numerator, denominator * x);
    result.reduceFraction();
    return result;
}
bool RationalNumber::operator<(const RationalNumber& r)
{
    if(this->floatingPoint < r.floatingPoint)
    {
        return true;
    }

    return false;
}

bool RationalNumber::operator<(int x)
{
    if(floatingPoint < (double) x)
    {
        return true;
    }

    return false;
}

bool RationalNumber::operator>(const RationalNumber& r)
{
    if(floatingPoint > r.floatingPoint)
    {
        return true;
    }
    return false;
}

bool RationalNumber::operator>(int x)
{
    if(floatingPoint > (double) x)
    {
        return true;
    }
    return false;
}

RationalNumber RationalNumber::operator+(const RationalNumber& r)
{
    RationalNumber result((numerator * r.denominator)+(r.numerator*denominator),denominator * r.denominator);
    result.reduceFraction();
    return result;
}

RationalNumber RationalNumber::operator+(int x)
{
    RationalNumber result(numerator * x,denominator);
    return result;
}

因此,这里有一个类,该类旨在用重载运算符表示有理数,这些重载运算符旨在执行算术运算。但是,在主类中时,请执行以下操作:

RationalNumber medianCalculator(std::vector<RationalNumber*> &listOfRationalNumbers)
{
    std::sort(listOfRationalNumbers.begin(),listOfRationalNumbers.end());
    if(!(listOfRationalNumbers.size() % 2)){
        return ((RationalNumber(*listOfRationalNumbers.at((listOfRationalNumbers.size()/2) +1)) + (RationalNumber(*listOfRationalNumbers.at(listOfRationalNumbers.size()/2))) / 2));
    } else {
        return RationalNumber(*listOfRationalNumbers.at(listOfRationalNumbers.size() +1));
    }
}

首先,它似乎生成了超出范围的异常,但更重要的是,似乎似乎操作符重载没有起作用,因为std :: sort调用似乎无效或算术运算。

1 个答案:

答案 0 :(得分:0)

肯定是运算符被错误地重载了。例如,此代码将产生意外的结果:

RationalNumber num(1, 1);
num *= 2;
// num is still 1/1

正确的实现应为:

RationalNumber& RationalNumber::operator*(int x)
{
    numerator *= x;
    reduceFraction();
    return *this;
}

其余方法应相应实施。