预测下面C++程序的输出:
#include <iostream> 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) {} // A method to compare two 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; }
输出:编译通过,产生输出。
Same
#include <iostream> using namespace std; class Complex { private: double real; double imag; public: // Default constructor explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} // A method to compare two 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; }
输出:编译错误。
no match for ‘operator==‘ in ‘com1 == 3.0e+0‘
我们仍然可以将double类型转换为Complex类型,但是现在我们必须要明确对它进行类型转换。例如,下面这个程序就工作正常。
#include <iostream> using namespace std; class Complex { private: double real; double imag; public: // Default constructor explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} // A method to compare two 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 == (Complex)3.0) cout << "Same"; else cout << "Not Same"; return 0; }
输出:编译通过,产生输出。
Same
原文:https://www.cnblogs.com/2018shawn/p/11465461.html