D
D
Daniil Romanov2020-05-04 18:00:04
C++ / C#
Daniil Romanov, 2020-05-04 18:00:04

What is the return type of the conversion operator?

Task text: Add a cast operator to double in the Rational class. All statements from the previous jobs are missing and do not need to be implemented. The to_double method can be used in this assignment.

struct Rational
{
    Rational(int numerator = 0, int denominator = 1);

    void add(Rational rational);
    void sub(Rational rational);
    void mul(Rational rational);
    void div(Rational rational);

    void neg();
    void inv();
    double to_double() const;
    
    operator double() const
    {
        return to_double();
    }

private:
    int numerator_;
    int denominator_;
};


Overloaded the double() operator. I don't understand one thing: why don't we use the return value here?
I don’t know such subtleties, but how can we return something (in this case, return to_double()), but not specify the return value?
When trying to specify a return value, double throws an error pointing to the word const.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Shatunov, 2020-05-04
@chattydude1

This is called a conversion operator .
The name of such an operator must be an explicitly defined qualified type that specifies the return type of the operator.
Accordingly, the return type is omitted (it cannot be specified). is redundant and will duplicate the operator name.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question