0

我是 C++ 的初学者,我不知道为什么 Rational r(2, 1) 的结果是“r == 0.5”,我发现 cotr 没有调用该operator()函数。为什么?

class Rational {
public:
    int numerator;
    int denominator;

  Rational(int a = 2, int b = 1)
    {
        cout<< "cotr"<<endl;
        numerator = a;
        denominator = b;
    };

    operator double() const
    {
        cout<< "()"<<endl;
        return (double)this->denominator/this->numerator;
    };

};

int main(int argc, const char * argv[])
{
    Rational r(2, 1);
    cout << "_____"<< endl;
    cout << r << endl;
    cout << r.numerator << " " << r.denominator << endl;
    double d = 0.5*r;
    cout << d;
    return 0;
}
4

1 回答 1

0

您将分母除以分子,将两者交换operator double() const:)

operator double() const
{
    cout<< "()"<<endl;
    return ((double)this->numerator)/this->denominator;
};

ctor 不会调用该operator double()函数,它仅在您尝试将您Rational转换为double. IE:

Rational frac(5, 7);
double result = (double)frac;

编辑

如果你想更好地控制你的输出,那么你可以重载 `operator<<' 这样你就可以将你自己的数据输入 cout。这是我实现它的方式:

在你的类定义中:

friend std::ostream& operator<< (std::ostream& stream, const Rational& ra);

并在您的源文件中的某处:

std::ostream& operator<< (std::ostream& stream, const Rational& ra)
{
    return stream << ra.numerator << ", " << ra.denominator;
    // or: return stream << (int)ra;
    // or: return stream << (double)ra;
}

然后你可以打电话:

cout << ra << endl;
于 2013-07-22T14:51:04.763 回答