类型转换构造函数
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
//用类型转换构造函数进行类型转换
class Point2D
{
public:
Point2D(int x, int y)
:_x(x), _y(y){}
friend class Point3D; //设置友元类
private:
int _x;
int _y;
};
class Point3D
{
public:
Point3D(int x, int y, int z)
:_x(x), _y(y), _z(z){}
#if 0
//我们把这一类,单参的构造器,称为类型转化构造器
//赋值 传参
类型转换构造函数,本质是一个构造函数.是只有一个参数的
构造函数,如有多个参数,只能称为构造函数,而不是转换函数.
#endif
//如果此构造器前面加上了explicit关键字 表示此转化需要
//以显示方式完成转化也就是p3=p2时需要显示强制转化
//p3 = static_cast<Point3D> (p2); 或者(Point3D)p2;
//implicit 是声明隐式 默认就是隐式的转化
Point3D(const Point2D &p2)
{
this->_x = p2._x;
this->_y = p2._y;
this->_z = 0;
}
//赋值重载函数可以利用默认的
Point3D &operator=(const Point3D &another)
{
this->_x = another._x;
this->_y = another._y;
this->_z = another._z;
return *this;
}
void dis()
{
cout << "(" << _x << "," << _y << "," << _z << ")"
<< endl;
}
private:
int _x;
int _y;
int _z;
};
int _tmain(int argc, _TCHAR* argv[])
{
Point2D p2(1, 2);
Point3D p3(3, 4, 5);
p3 = p2;
//此处先调用了类型转化的构造器,将p2(Point2D类型)转为Point3D类型
//然后再调用了赋值运算符重载函数,将转化后的p2赋值给p3
p3.dis();
return 0;
}