特殊的类型转换(单参构造,运算符重载)

#include<iostream>
//#include<stdio.h>
using namespace std;
class Test1{
public:
	Test1(void){//无参构造  缺省构造 
		num = 0;
	}
	Test1(int n){
		cout << "Test1::constructor" << endl;
		num = n;
	}
	int & value(){
		return num;
	}
private:
	int num;
};
class Test2{
public:
	explicit Test2(int n){
		cout << "Test2::constructor" << endl;
		num = n;
	}
	int &value(){
		return num;
	}
private:
	int num;
};


class Test3 {
public:
	 Test3(int n,int num111 = 0) {//这种情况也可能发生单参构造的类型转换
		cout << "Test3::constructor" << endl;
		num = n;
		num1 = num111;
	}
	int &value() {
		return num;
	}
private:
	int num;
	int num1;
};

int main(){
	Test1 t1;
	cout << t1.value() << endl;
	Test1 t2(100);
	cout << t2.value() << endl;
	t2 = 1000;//t2 = Test1(1000);隐式类型转换
	cout << t2.value() << endl;
	Test2 T2(100);
	cout << T2.value() << endl;
	//T2 = 1000;//error  二进制“=”: 没有找到接受“int”类型的右操作数的运算符(或没有可接受的转换)
	T2 = Test2(1000);//只能显式的转换
	cout << T2.value() << endl;

	Test3 t3(100, 200); 
	t3 = 250;
	cout << t3.value() << endl;
	getchar();
	return 0;
}


#include<iostream>
using namespace std;

class Pointer2D
{
public:
	Pointer2D(int x,int y):m_x(x),m_y(y){}
private:
	int m_x;
	int m_y;
	friend class Pointer3D;
	friend ostream & operator<<(ostream&os,Pointer2D const &p2);
};
class Pointer3D
{
public:
	Pointer3D(int x,int y,int z):m_x(x),m_y(y),m_z(z){}

	//在目标类型中定义从源类型的类型转换构造函数(拷贝构造) 
	Pointer3D(Pointer2D const &p2):m_x(p2.m_x),m_y(p2.m_y),m_z(0)
	{
		cout<<"Pointer3D(Pointer2D const &p2)"<<endl;
	}//p3 = p2

	//在源类型中定义到目标类型的类型转换运算符函数
	operator Pointer2D(void)const
	{
		cout<<"perator Pointer2D(void)const"<<endl;
		return Pointer2D(m_x,m_y);//
	}
	friend ostream & operator<<(ostream&os,Pointer3D const &p3);
private:
	int m_x;
	int m_y;
	int m_z;
};
ostream & operator<<(ostream&os,Pointer3D const &p3)
{
	return os<<p3.m_x<<" "<<p3.m_y<<" "<<p3.m_z<<endl;
	
}
ostream & operator<<(ostream&os,Pointer2D const &p2)
{
	return os<<p2.m_x<<" "<<p2.m_y<<endl;
}
class Integer
{
public:
	Integer(int i = 0):m_i(i){}
	operator int (void)const{
		return m_i;
	}
private:
	int m_i;
};
int main(){

	Pointer2D p2(1,2);
	cout<<p2<<endl;

	Pointer3D p3(4,5,6);
	cout<<p3<<endl;

	Pointer3D p31 = p2;//Pointer3D(Pointer2D const &p2)
	cout<<p31<<endl; 

	p2 = p3;//p3.operator Pointer2D()

	//cout<<p2<<endl;//4 5 

	getchar();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值