當一個構造函數只有一個參數,而且該參數又不是本類的const引用時,這種構造函數稱為轉換構造函數。
參考一下示例:
// TypeSwitch.cpp : Defines the entry point for the console application. // #include "stdafx.h" #includeusing namespace std; class Complex { public: Complex():real(0),imag(0){}; Complex(double r, double i):real(r), imag(i){}; //1> 轉換構造函數 Complex(double r):real(r),imag(0) { cout<<"轉換構造函數被調用。 \n"; }; void Print() { cout<< "real = " << real << " image = " << imag<< endl; } Complex& operator+(const Complex &cl) { this->real += cl.real; this->imag += cl.imag; return *this; } //2> = 賦值運算重載 // Complex& operator = (double i) // { // this->real = 0; // this->imag = i; // cout<<"賦值運算重載被調用"< 轉換構造函數被調用;如果1>,2>都存在,2> = 賦值運算重載會被調用; cl.Print();//1>的時候,real = 1.5 imag = 0; 1>,2>的時候,real = 0 imag = 1.5; cl = Complex(2,3);//構造函數Complex(double r, double i)被調用後,調用默認=賦值運算; cl.Print();//real = 2 imag = 3; cl = Complex(1, 1) + 2.5;//1>轉換構造函數被調用;如果1>,2>都存在,1>轉換構造函數被調用 cl.Print();//real = 3.5 imag = 1; return 0; }