问题引入:
对于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;
}