解析C++转换构造函数(调用规则)

来源:互联网 发布:淘宝上的aj是正品吗 编辑:程序博客网 时间:2024/06/11 20:36

什么叫转换构造函数?


当一个构造函数只有一个参数,而且该参数又不是本类的const引用时,这种构造函数称为转换构造函数。


参考一下示例:


// TypeSwitch.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <IOSTREAM>using 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<<"赋值运算重载被调用"<<endl;// return *this;// }private:double real;double imag;};int main(int argc, char* argv[]){Complex cl;//构造函数Complex()被调用;cl.Print();//real = 0 imag = 0;cl = 1.5;  //1>转换构造函数被调用;如果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;}


P.S注释已经很详细,如果不清楚,可以自己debug一下。


1 0
原创粉丝点击