自定义数据类型之间的相互转换和explicit关键字(C++)

问题引入:

  对于C++类型系统提供的基本数据类型,只需按照C++对于的语法规则进行转换即可,但是对于用户自定义的数据类型,例如一个自定义的类,该如何转换?

解决方法:2种。
 法一:使用类型转换构造函数,只有一个参数,在目标类型里面写实现代码。
目标类型(const 源类型 &)
{
	目标类型成员变量赋值代码;
}

例如:将double转换为复数类Complex:源类型double,目标类型Complex

//加explicit实现用户显示指定转换类型,显示调用 
explicit Complex(const double& r){
	real_ = r;  //实部
	imag_ = rand()%100; //虚部
}  
 法二:重载类型强制转换运算符,在源类型里面写代码,只能重载为成员函数,且其为单目运算符。
operator 目标类型()
{
	return 目标类型(构造函数参数列表);
}

例如:将Complex转换为double类型,源类型Complex,目标类型double。

operator double()
{
	return this->real_;
}

  完整的复数类与浮点型相互转换代码

#include<iostream>
using namespace std;

class Complex{
public:
	friend ostream& operator<<(ostream& os, const Complex& c);
	Complex(double r, double i)
		: real_(r), imag_(i){}
		
	//1.将double转换为Complex:源类型double,目标类型Complex
	//加explicit实现用户显示指定转换类型,显示调用 
	explicit Complex(const double& r); 
	
	//2.将Complex转为double:源类型Complex,目标类型double
	operator double(){
		cout << "重载强制类型转换" << endl;
		return this->real_;
	} 
private:
	double real_;
	double imag_;
};

Complex::Complex(const double& r){
	real_ = r;
	imag_ = rand()%100;
	cout << "类型转换构造函数\n"; 
}  

ostream& operator<<(ostream& os, const Complex& c){
	cout << c.real_ << "+" << c.imag_ << "i";
}

void test01(){
	//double到Complex
	double d = 10;
	Complex c(0,0);
	c = static_cast<Complex>(d); //static_cast<type>()实现显示转换,显示调用 
	cout << "c: " << c << endl;
	
	d = 20;
	c = (Complex)d;  //c语言风格,(type)实现显示转换 
	cout << "c: " << c << endl;
	
	d = 30;
	c = Complex(d); //c++风格,type() 
	cout << "c: " << c << endl;
	
	d = 40;
	Complex c1(d);
	cout << "c1: " << c1 << endl;
	
	d = 50 ;
	//c1 = d; //隐式转换,编译出错
	//如果不加explicit关键字,可以隐式转换。 
}

void test02(){
	//将Complex转为double 
	Complex c(10,20);
	double d = 100 + c; //100 + c.operator double()
	cout << "d= " << d << endl;
}

int main(){
	test01();
	cout << "------------------------" << endl;
	test02();

	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值