c++ - cout a class object using conversion operator -
#include <iostream> #include <cmath> using namespace std; class complex { private: double real; double imag; public: // default constructor complex(double r = 0.0, double = 0.0) : real(r), imag(i) {} // magnitude : usual function style double mag() { return getmag(); } // magnitude : conversion operator operator int () { return getmag(); } private: // class helper magnitude double getmag() { return sqrt(real * real + imag * imag); } }; int main() { // complex object complex com(3.0, 4.0); // print magnitude cout << com.mag() << endl; // same can done cout << com << endl; }
i don't understand how compiler resolving call conversion operator cout << com << endl;
.
i can have more 1 conversion operator in same class. how resolution done in case?
you have declared conversion operator int
. since operator not explicit, compiler considers when finding best overload of ostream::operator<<
. keep in mind c++ compiler attempts automatically convert types find matching call, including conversion constructors, conversion operators , implicit type conversions.
if not want behavior, starting c++11 can mark operator explicit
:
explicit operator int() { return getmag(); }
regarding second part of question, if there multiple conversions equally good, compile error invoked. if added, say, operator double
, there exists ostream::operator(double)
, call ambiguous , need cast com
desired type.
Comments
Post a Comment