[ 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): 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); double d = frac;
QString fs = frac;
cout << "fs= " << fs << " d=" << d << endl; cout << frac << endl;
return 0; }
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
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |