19.8.1.  Conversion Operators

[ fromfile: useroperators.xml id: conversionoperators ]

We saw earlier in Section 2.13 that user defined conversions can be introduced into the compiler's type system through the use of conversion constructors. This makes it possible to convert from a basic type to a non-basic type. To define a conversion in the opposite direction, a conversion operator is needed. In Section 5.4, we saw how to define the behavior of operators on non-simple types. A conversion operator is simply an overloaded operator where the operator is a typecast.

Example 19.6. src/operators/fraction/fraction-operators.cpp

#include <QString>
#include <QTextStream>

QTextStream cout(stdout);

class Fraction {
public:
    Fraction(int n, int d = 1)   1 
        : m_Numerator(n), m_Denominator(d) {}

    operator double() const { 2
        return (double) m_Numerator / m_Denominator;
    }  
    
    operator QString () const {
        return  QString("%1/%2").arg(m_Numerator).arg(m_Denominator);
    }
private:
    int m_Numerator, m_Denominator;
};

QTextStream& operator<< (QTextStream& os, const Fraction& f) {
    os << static_cast<QString> (f); 3
    return os;
}

int main() {
    
    Fraction frac(1,3);
    double d = frac; 4
    QString fs = frac; 5
    cout  << "fs= " << fs << "  d=" << d << endl;
    cout  << frac << endl; 6
    return 0;
}

1

conversion constructor

2

conversion operator

3

calls conversion operator

4

calls conversion operator

5

another conversion

6

no conversion - calls operator << directly.

The last When the program in Example 19.6 is run, we can see the use of a user defined conversion from Fraction to double.

 frac= 1/3  d=0.333333