Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

c++ - What are the conversion constructors

class Complex
{
private:
double real;
double imag;

public:
// Default constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

// A method to compare to Complex numbers
bool operator == (Complex rhs) {
   return (real == rhs.real && imag == rhs.imag)? true : false;
}
};

int main()
{
// a Complex object
Complex com1(3.0, 0.0);

if (com1 == 3.0)
   cout << "Same";
else
   cout << "Not Same";
 return 0;
}

Output: Same

Why this code gives output as Same, how the conversion constructor in working here, please explain, Many many thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A conversion constructor is any non-explicit constructor callable with one argument. In your code sample, as the Complex constructor provides default values for its parameters, it can be called with a single argument (say 3.0). And since such constructor is not marked explicit, then it is a valid conversion constructor.

When you do com1 == 3.0 --given that there is no operator == between Complex and double-- a conversion constructor is invoked. So your code is equivalent to this:

if( com1 == Complex(3.0) )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...