这两种之间的转换主要有两种方式第一就是内置类型转换为用户自定义类型,这里以int类型转换为类类型的对象为例,第二就是类类型转换为int类型
前者依靠转换构造函数,后者依靠自定义的类型转换函数
一.转换构造函数
二.类型转换构造函数
#include <iostream>
using namespace std;
//转换构造函数只有一个参数,但是有时候这种一个参数的构造函数不仅起到类型转换的作用也起到了构造函数的作用,但是只有一个参数的构造函数才有这种类似的双重身份,并且这种没有拷贝构造的情况就调用默认拷贝构造
class Trans
{
private:
int m_data;
public:
Trans(const Trans &t)
{
cout<<"Copy Test Obj : "<<this<<"\n";
m_data = t.m_data;
}
Trans& operator=(const Trans &t)
{
cout<<"Assgin:"<<this<<" : "<<&t<<"\n";
if(this != &t)
{
m_data = t.m_data;
}
return *this;
}
~Trans()
{
cout<<"Free S Obj :"<<this<<"\n";
}
//重点在底下的函数
Trans(int=0);
operator int();
void show();
};
int main()
{
cout<<"-------转换构造函数------------\n";
Trans X=Trans(3);//调用构造函数生成一个临时无名对象之后调用拷贝构造函数进行
X.show();
Trans X1=6;//同上
X1.show();
X1=8;//这里同上只是调用赋值函数
X1.show();
cout<<"-------类型转换函数------------\n";
Trans Y(99),Y1(1);
Trans Y2;
Y2=Y1+Y;//没有+运算符的重载,编译器就会找到类型转换函数将两个对象转换为数值之后相加然后用相加的值构造一个临时对象再调用赋值函数给Y2
Y2.show();
int a=0;
a=Y2;
cout<<a<<"\n";
return 0;
}
Trans::Trans(int n):m_data(n)
{
cout<<"Ctor the obj!"<<this<<"\n";
}
Trans::operator int()
{
cout<<"Operator obj to int !"<<this<<"\n";
return m_data;
}
void Trans::show()
{
cout<<"Data is: "<<m_data<<" Obj is: "<<this<<"\n";
}