C++类型转换 -- 由其他类型转换到自定义类型

由其他类型转换到自定义类型

由其他类型(如int,double)向自定义类的转换是由构造函数来实现,只有当类的定义和实现中提供了合适的构造函数,转换才能通过。

 /***********************main.c****************/
#include <iostream.h>
using namespace std;
class anotherPoint
{
private:
double x;
double y;
public:
anthorPoint(double xx=,double yy=)
{
x =xx;
y = yy;
}
double getX()
{
return x;
}
double getY()
{
return y;
}
}; class point
{
private:
int xPos;
int yPos;
public:
point(int x =,int y = )
{
xPos = x;
yPos = y;
}
point(authorPoint sP) //构造函数,参数为anthorPoint对象
{
xPos = aP.getX();
yPos = aP.getY();
}
void print()
{
cout<<"( "<<xPos<<" , "<<yPos<<" , "<<endl;
}
}; int main()
{
point p1;
p1 = ; //等价于p1 = point(5,0);
p1.print();
double dX = 1.2;
p1 = dX; //等价于p1 = point(int(dX),0);
p1.print(); anthorPoint p2;
p1 = p2; //等价于 p1 = point(p2);
p1.print();
return ;
}

输出结果如下:

(  ,  )
( , )
( , )

代码中第57行,构造函数“point(authorPoint aP)”被调用,先生成一个临时point类对象,再调用赋值运算符完成对p1的赋值。

隐式转换往往会出现一些意想不到的问题,使用关键字“explicit”可有效阻止隐式类型的转换,将36行改写为

explict   point(anthorPoint  aP)

那么57行语句就会被编译器认定为非法,必须使用显示转换

p1 = (point)p2;
上一篇:C# 字符串string类型转换成DateTime类型 或者 string转换成DateTime?(字符串转换成可空日期类型)


下一篇:Java byte类型转换成int类型时需要 & 0XFF的原因