19.9.1.  Conversion Operators

[ fromfile: useroperators.xml id: conversionoperators ]

Example 19.13. 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);
    Fraction frac2(4);                  4
    double d = frac;                    5
    QString fs = frac;                  6
    cout << "fs= " << fs << "  d=" << d << endl;
    cout << frac << endl;               7
    cout << frac2 << endl;
    return 0;
}

1

Conversion constructor.

2

Conversion operator.

3

Explicit cast calls conversion operator.

4

Conversion constructor call.

5

Calls conversion operator.

6

Another conversion operator call.

7

Operator<<() called directly.


 src/operators/fraction> ./fraction
 fs= 1/3  d=0.333333
 1/3
 4/1
 src/operators/fraction>