类型转换:将一种类型的值转换为另一种类型的值
类类型:class、stuct、union类型
标准类型:除类类型外的所有类型,如int
类型种类:
类型转换有4种:
1)标准类型->标准类型
2)标准类型->类类型
3)类类型->标准类型
4)类类型->类类型
一、标准类型转变为标准类型
方法:
1)隐式转换
使用场合:程序未显式类型转换,但是含有混合运算,赋值语句,函数返回值,形参和实参转换
2)显式转换
使用场合:程序显式类型转换
方法:C语言的强制法(int)a和C++的函数法int(a)
注意:当类型名有两个以上时(unsign int ),不能使用C++的函数法,但是可以使用C语言的强制法,所以以后可以直接使用C的强制法,不会错
二、标准类型转化成类类型
方法:构造函数和自定义的重载赋值号=的函数
必备参数:它们都需要有标准类型的参数(这个标准类型就是等号右边的值类型)
代码:
#include <iostream>
using namespace std;
class String
{
private:
int len;
char* strContent;
public:
String(int i);
String(char* p);
String& operator=(int i);
String& operator=(char* p);
void show();
};
String::String(int i)
{
len=i;
strContent = new char[len];
memcpy(strContent,"",len);
}
String::String(char* p)
{
len=strlen(p)+1;
strContent = new char[len];
memcpy(strContent,p,len);
}
String& String::operator=(int i)
{
len=i;
if (strContent!=NULL)
{
delete []strContent;
}
strContent = new char[len];
memcpy(strContent,"",len);
return *this;
}
String& String::operator=(char* p)
{
len=strlen(p)+1;
if (strContent!=NULL)
{
delete []strContent;
}
strContent = new char[len];
memcpy(strContent,p,len);
return *this;
}
void String::show()
{
cout<<"字符串长度为:"<<len<<endl;
cout<<"字符串内容为:"<<strContent<<endl;
}
void main()
{
String a=1;//调用构造函数
a.show();
String b="123";//调用构造函数
b.show();
b=6; //调用重载运算符=
b.show();
b="456";//调用重载运算符=
b.show();
system("pause");
}
注意:为了避免标准类型隐式转换为类类型(OBJ obj=20),可以把构造函数放在私有段,在创建对象的时候就不能直接调用构造函数了,
这时创建对象可以通过定义一个静态成员函数或一个友元函数 来间接调用构造函数来
代码:
#include <iostream>
using namespace std;
class String
{
private:
int len;
char* strContent;
String(char* p);
public:
static String make(char* p);
void show();
};
String::String(char* p)
{
len=strlen(p)+1;
strContent = new char[len];
memcpy(strContent,p,len);
}
String String::make(char* p)
{
String a=p;//创建一个类,并调用构造函数
return a;
}
void String::show()
{
cout<<"字符串长度为:"<<len<<endl;
cout<<"字符串内容为:"<<strContent<<endl;
}
void main()
{
String a="123";//错误
String a = String::make("123456");
a.show();
system("pause");
}
三、类类型->标准类型 和 类类型->类类型
方法:引入特殊的成员函数---类型转换函数
类型转换函数:在类对象之间提供一种类似显式类型转换的机制。
语法:
Class 源类类名 //在此类中定义
{
Operator 目的类型()
{
Return 目的类型的数据;
}
}
作用:将对象转换成目的类型的变量,目的类型如果是标准类型也可以是类类型
注意一:类型转换函数没有参数、没有返回类型、但是有返回值(一个type的实例)。
注意二、类型转换函数只能定义为类的成员函数,而不能是友元函数(不允许有参数)
注意三、类型转换函数不可以被超载,因为没有参数
代码:
#include <iostream>
using namespace std;
class point
{
private:
int x;
public:
point()
{
x=10;
}
operator int() //类型转换函数,转换为整型
{
return x;
}
};
void main()
{
point a;
int t=a;//隐式调用 类型转换函数
cout<<t<<endl;
int z = a.operator int();//显示调用 类型转换函数
cout<<z<<endl;
system("pause");
}
注意一:一般使用隐式方式,当需要明确指出用哪一个类型转换函数时,才使用显式方式
注意二:注意下面两种转换方式:
int a = obj;//使用类型转换函数进行转换
OBJ obj=a; //使用构造函数进行转换
注意三、当一个类既有用于转换的构造函数,又拥有类型转换函数
如:
构造函数:A(int a);
类型转换函数:operator int( )
则,obj=obj+n 就有两种解释:类和标准类型可以互相转化,隐式转换有二义性
解释一:可以先把对象转换为数,再两个数相加
解释二:可以先把数转换成类,再相加
解决方法:这是需要显示使用类型转换函数:
方法一:先把数变对象,两个对象再相加
INT obj1=n;Obj=obj+obj1 两个对象相加
方法二:先把对象变数,两个整数再相加
Obj=(int)obj+n;
即:用户类型定义的类型转换函数,只有无二义性的时候,才能使用隐式转换