#include <iostream>
#include <cmath>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
// Default constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i)
{}
// magnitude : usual function style
double mag()
{
return getMag();
}
// magnitude : conversion operator
operator int ()
{
return getMag();
}
private:
// class helper to get magnitude
double getMag()
{
return sqrt(real * real + imag * imag);
}
};
int main()
{
// a Complex object
Complex com(3.0, 4.0);
// print magnitude
cout << com.mag() << endl;
// same can be done like this
cout << com << endl;
}
I don't understand how the compiler is resolving to call the conversion operator for cout << com << endl;
.
I can also have more than one conversion operator in the same class. How will the resolution be done in that case?
You have declared a conversion operator to int
. Since this operator is not explicit, the compiler considers it when finding the best overload of ostream::operator<<
. Keep in mind that C++ compiler always attempts to automatically convert types to find a matching call, including conversion constructors, conversion operators and implicit type conversions.
If you do not want this behavior, then starting from C++11 you can mark the operator as explicit
:
explicit operator int() {
return getMag();
}
Regarding the second part of your question, if there are multiple conversions that are equally good, a compile error is invoked. If you added, say, operator double
, then as there exists ostream::operator(double)
, the call would be ambiguous and you would need to cast com
to Your desired type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With