[ fromfile: useroperators.xml id: conversionoperators ]
you can introduce type conversions into the compiler's type system through the use of conversion constructors.
This makes it possible to convert from an already existing type to a new type.
A conversion operator looks quite different from other member functions.
It has no return type (not even void
) and no parameters.
When a conversion operator is applied, it returns an object of its named type: a conversion of the host object as specified in the function body.
When the program in Example 19.13 is run, you can see the use of user-defined conversions from Fraction
to double
and to QString.
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) : m_Numerator(n), m_Denominator(d) {} operator double() const { 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); return os; } int main() { Fraction frac(1,3); Fraction frac2(4); double d = frac; QString fs = frac; cout << "fs= " << fs << " d=" << d << endl; cout << frac << endl; cout << frac2 << endl; return 0; }
src/operators/fraction> ./fraction fs= 1/3 d=0.333333 1/3 4/1 src/operators/fraction>
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |