//复制构造函数只有一个参数,即对同类对象的引用 // #include <iostream> using namespace std; class Complex{ private: double real, imag; public: Complex(){ cout << "调用缺省无参构造函数" << endl; } Complex(const Complex & c){ real = c.real; imag = c.imag; cout << "Copy Constructor called"; } }; int main(){ Complex c1; //调用缺省无参构造函数 Complex c2(c1); //调用缺省的复制构造函数,将c2初始化和c1一样 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对象 cout << c1.real << "," << c1.imag << endl; return 0; }
输出:
Structor is called
7,8
IntConstructor called
9,0