使用一个不同的类初始化另外一个类,这种情况是要经过类型转换才能完成的,否则语法上就无法通过。同样,类的类型转化也分隐式转换和显式转换。以下代码介绍了隐式转换和显式转换的两种方法。以及 explicit 关键字的使用。

#include

using namespace std;

class Point2D
{
public:
Point2D(int x, int y)
:_x(x), _y(y) {}

friend ostream& operator<<(ostream& os, const Point2D& p)
{
os << “(“ << p._x << “, “ << p._y << “)” << endl;
return os;
}

friend class Point3D;

private:
int _x;
int _y;
};

class Point3D
{
public:
Point3D(int x, int y, int z)
:_x(x), _y(y), _z(z) {}

// 通过构造器将一个非构造器类型的对象转化为构造器类型对象
explicit Point3D(Point2D& p2)
{
this->_x = p2._x;
this->_y = p2._y;
this->_z = 0;
}

Point3D operator+(const Point3D &one)
{
Point3D tmp(0, 0, 0);
tmp._x = this->_x + one._x;
tmp._y = this->_y + one._y;
tmp._z = this->_z + one._z;
return tmp;
}

friend ostream& operator<<(ostream& os, const Point3D& p)
{
os << “(“ << p._x << “, “ << p._y << “, “ << p._z << “)” << endl;
return os;
}

private:
int _x;
int _y;
int _z;
};

int main(int argc, char* argv[])
{
Point2D p2(2, 3);
cout << p2;

Point3D p3(7, 8, 9);
cout << p3;

// 通过构造器将一个非构造器类型的对象转化为构造器类型对象
// 没加 explicit 关键字时,类似于C语言中的隐式转化
// Point3D p3a = p2;
// cout << p3a;

// 加了 explicit 关键字后,显式转换
Point3D p3a = static_cast(p2);

// 先走类型转换构造器,然后再走+运算符重载
Point3D p4a = p3 + static_cast(p2);
cout << p4a << endl;

return 0;
}