First, let’s look at the output of the following C ++ program.

#include <iostream>using namespace std; class Complex{private:double real; double imag; Public :// Default constructorComplex(double r = 0.0, double I = 0.0) : real(r), imag(i) {}// A method to compare two Complex numbersbool operator == (Complex rhs) {return (real == rhs.real && imag == rhs.imag)? true : false; }}; Int main(){// a Complex objectcom1 (3.0, 0.0); If (com1 == 3.0)cout << "Same"; elsecout << "Not Same"; return 0; }Copy the code

Output: The program compiles normally and produces the following output.

Same

In C ++, if a class has a constructor that can be called with a single argument, that constructor becomes a transformation constructor, because such a constructor allows a single argument to be converted to the class being constructed.

We can avoid such implicit conversions because they can lead to unexpected results. For example, if you try the following program that uses an explicit keyword with a constructor, you get a compilation error.

#include <iostream>using namespace std; class Complex{private:double real; double imag; Public :// Default constructors Complex(double r = 0.0, double I = 0.0) : real(r), imag(i) {}// A method to compare two Complex numbersbool operator== (Complex rhs) {return (real == rhs.real && imag == rhs.imag)? true : false; }}; Int main(){// a Complex objectcom1 (3.0, 0.0); If (com1 == 3.0)cout << "Same"; elsecout << "Not Same"; return 0; }Copy the code

Output: Compiler error

No match for ‘operator ==’ was found in ‘com1 == 3.0e + 0’

We can still convert the double value type to Complex, but now we have to explicitly cast it. For example, the following program works fine.

#include <iostream>using namespace std; class Complex{private:double real; double imag; Public :// Default constructors Complex(double r = 0.0, double I = 0.0) : real(r), imag(i) {}// A method to compare two Complex numbersbool operator== (Complex rhs) {return (real == rhs.real && imag == rhs.imag)? true : false; }}; Int main(){// a Complex objectcom1 (3.0, 0.0); If (com1 == (Complex)3.0)cout << "Same"; elsecout << "Not Same"; return 0; }Copy the code

Output: The program compiles normally and produces the following output.

Same

And that’s all for today. I hope I can help you

In addition, if you want to improve your programming ability, learn C language C++ programming! Overtake on the curve, one step faster! The author here may be able to help you ~

C language C++ programming learning exchange circle, **QQ group [951258402] ** wechat public number: C language programming learning base

Share (source code, project actual combat video, project notes, basic introduction tutorial)

Welcome to change careers and learn programming partners, use more information to learn and grow faster than their own thinking oh!

Programming learning video sharing: