//显式类型转换构造函数 #include <iostream> using namespace std; class Complex{ public: double real, imag; explicit Complex(int i){ //显式类型转换构造函数 cout << "IntConstructor called" << endl; real = i; imag = 0; } Complex(double r, double i){ //构造函数 real = r; imag = i; cout << "Structor is called" << endl; } }; int main(){ Complex c1(7, 8); Complex c2 = c1; cout << c2.real << "," << c2.imag << endl; //c1 = 9; //ERROR,9不能被自动转换成一个临时complex对象 c1 = Complex(9); cout << c1.real << "," << c1.imag << endl; return 0; }
//隐式类型转换构造函数 #include <iostream> using namespace std; class Complex{ public: double real, imag; Complex(int i){ //类型转换构造函数 cout << "IntConstructor called" << endl; real = i; imag = 0; } Complex(double r, double i){ //构造函数 real = r; imag = i; cout << "Structor is called" << endl; } }; int main(){ Complex c1(7, 8); Complex c2 = c1; cout << c2.real << "," << c2.imag << endl; c1 = 9; //9被自动转换成一个临时complex对象 //c1 = Complex(9); cout << c1.real << "," << c1.imag << endl; return 0; }