用转换构造函数进行类型转换
主要用于其它类型到本类类型的转化。
- 转换构造函数格式
class 目标类型
{
目标类型(const 源类型 & 源类型变量/对象引用)
{
根据需求完成从源类型到目标类型的转换
}
}
-
特点
转换构造函数,本质是一个构造函数。是只有一个参数的构造函数。如有多个参数,
只能称为构造函数,而不是转换函数。 -
代码举例
#include <iostream>
using namespace std;
class Point3D;
class Point2D
{
public:
Point2D(int x, int y) : _x(x), _y(y) {}
void dis()
{
cout << "(" << _x << "," << _y << ")" << endl;
}
friend Point3D; //friend Point3D::Point3D( Point2D &p2);
private:
int _x;
int _y;
};
class Point3D
{
public:
Point3D(int x, int y, int z) : _x(x), _y(y), _z(z) {}
Point3D(Point2D &p)
{
this->_x = p._x;
this->_y = p._y;
this->_z = 0;
}
void dis()
{
cout << "(" << _x << "," << _y << "," << _z << ")" << endl;
}
private:
int _x;
int _y;
int _z;
};
int main()
{
Point2D p2(1, 2);
p2.dis();
Point3D p3(3, 4, 5);
p3.dis();
Point3D p3a = p2;
p3a.dis();
return 0;
}
explicit关键字
在构造函数声明中使用explicit可防止隐式转换,而只允许强制类型转换。
如在上面代码中加入explicit关键字后:
explicit Point3D(Point2D &p)
{
this->_x = p._x;
this->_y = p._y;
this->_z = 0;
}
...
Point3D p3a = p2; //error,无法实现隐式转换
Point3D p3a = (Point3D)p2; //right 强制类型转换
转换函数
-
转换函数格式
class 源类型 { operator 转化目标类型(void) { 根据需求完成从源类型到目标类型的转换 } }
-
特点
转换函数必须是类方法,转换函数无参数,无返回
-
代码举例
#include <iostream> using namespace std; class Point3D; class Point2D { public: Point2D(int x, int y) : _x(x), _y(y) {} operator Point3D(); void dis() { cout << "(" << _x << "," << _y << ")" << endl; } private: int _x; int _y; }; class Point3D { public: Point3D(int x, int y, int z) : _x(x), _y(y), _z(z) {} void dis() { cout << "(" << _x << "," << _y << "," << _z << ")" << endl; } private: int _x; int _y; int _z; }; Point2D::operator Point3D() { return Point3D(_x, _y, 0); } int main() { Point2D p2(1, 2); p2.dis(); Point3D p3(3, 4, 5); p3.dis(); Point3D p3a = p2; p3a.dis(); return 0; }
网友评论