C++类*类型和其他类型相互转换

类类型转换时会出现两种之间转换,下面我们说的是类类型

1.其他类型转换为本类类型

   通过类带一个参数的构造函数;或者多个参数构造函数,除了第一个参数后面参数都有默认值时!这样在其他类型赋值给该类类型对象时会发生隐式转换。

#include <string>
#include <iostream>
using namespace std;
class Test
{
public:
	int m_i = 10;
	/*explicit*/ Test(int i):m_i(i)		// explicit可以杜绝隐式转换
	{
		cout << "构造" << endl;
	}
	~Test()
	{
		cout << "析构" << endl;
	}
	
};

int main()
{
	Test t1 = 100;	// 隐式转换

	return 0;
}

  explicit可以杜绝这种隐式转换,这样限制后就只能显式的转换了!

2.本类类型转换其他类型

   通过类的《转换操作符》来完成,转换操作符是一种特殊的类成员函数,它可以将类类型转换为其他类型值的转换。如下:

  operator    type()  

   type:需要转换的其他类类型(void除外

   转换函数必须是成员函数,不能指定返回类型,并且形参表必须为空

#include <string>
#include <iostream>
using namespace std;
class Test
{
public:
	int m_i = 10;
	explicit Test(int i):m_i(i)		// explicit可以杜绝隐式转换
	{
		cout << "构造" << endl;
	}
	
	// 本类类型自动隐式转换int类型 
	operator int() const { return m_i;} // 本类类型转换其他类型 

	~Test()
	{
		cout << "析构" << endl;
	}
	
};

int main()
{
	//Test t1 = 100;	// erro
	Test t1(1000);
	int s = t1;        //t1转换为int
	cout << s << endl;
	return 0;
}

 

posted @ 2019-04-09 02:49  jadeshu  阅读(197)  评论(0编辑  收藏  举报