类型转换构造函数

类型转换构造函数

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值