class 目标类 { 目标类(const 源类型 & 源类对象引用) { 根据需求完成从源类型到目标类型的转换 } } 目标 实现其它类型到本类类型的转化。 原理 转换构造函数,本质是一个构造函数。是只有一个参数的构造函数。如有多 个参数,只能称为构造函数,而不是转换函数。转换构造,强调的是一转一。 应用 用于传参或是作返回。
关键字 explicit 可以禁止"单参数构造函数"被用于自动类型转换。
即 explicit 仅用于单参构造(默认参数构成的单参亦算)。
转化多是刻意而为之,以隐式的形式发生,为了示意同正常构造的不同,常用
explicti 关键字修饰,要求在转化时显示的调用其构造器完成转化。
#include #include #include using namespace std; //转化构造函数的本质,也是构造函数 class Point2D { //友元类 friend class Point3D; public: Point2D(int x=0, int y=0 ) :_x(x),_y(y){} private: int _x; int _y; }; class Point3D { public: Point3D(int x=0, int y=0 ,int z=0) :_x(x),_y(y),_z(z){} //转换构造函数 explicit Point3D(const Point2D & d2) { this->_x = d2._x; this->_y = d2._y; this->_z = rand()%100; } void dumpFormat() { cout<<"("<<_x<<","<<_y<<","<<_z<<")"<
```c++ #include using namespace std; //关键字 explicit 可以禁止"单参数构造函数"被用于自动类型转换 class mystring { public: explicit mystring(const char* s= nullptr) { cout<<" mystring(const char* s= nullptr)"<
## 自定义类型-操作符函数转化 转换函数必须是类方法,转换函数无参数,无返回。 ```c++ class 源类{ operator 目标类(void) { return 目标类构造器(源类实参); } }
//todo 自定义类型-操作符函数转化 #include #include #include using namespace std; class Point3D { public: Point3D(int x=0, int y=0 ,int z=0) :_x(x),_y(y),_z(z){} void dumpFormat() { cout<<"("<<_x<<","<<_y<<","<<_z<<")"<
上一篇:5行代码快速Git配置ssh
下一篇:银河麒麟高级服务器操作系统V10SP2(X86)xshell连接之后主动断开,报错socket error event:32 Error:10053问题分析