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

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

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

 1 /***********************main.c****************/
 2 #include <iostream.h>
 3 using namespace std;
 4 class  anotherPoint
 5 {
 6     private: 
 7          double  x;
 8          double  y;
 9     public:
10          anthorPoint(double xx=1,double yy=1)
11         {
12              x =xx;
13              y = yy;
14         }
15        double  getX()
16        {
17             return x;
18        }
19        double getY()
20        {
21             return y;
22        }
23 };
24 
25 class point
26 {
27     private:
28          int xPos;
29          int yPos;
30     public:
31          point(int x =0,int y = 0)
32          {
33              xPos  = x;
34              yPos  = y;
35          }
36          point(authorPoint sP)     //构造函数,参数为anthorPoint对象
37          {
38              xPos  = aP.getX();
39              yPos  = aP.getY();
40          }
41         void  print()
42         {
43              cout<<"(  "<<xPos<<"  ,  "<<yPos<<"  ,  "<<endl;
44         }
45 };
46 
47 int main()
48 {
49     point p1;
50     p1 = 5;                //等价于p1 = point(5,0);
51     p1.print();
52     double dX = 1.2;
53     p1 = dX;              //等价于p1 = point(int(dX),0);
54     p1.print();
55 
56     anthorPoint p2;
57     p1 = p2;              //等价于 p1 = point(p2);
58     p1.print();
59     return 0;
60 }

输出结果如下:

5 , 0 )
( 1 , 0 )
( 1 , 1

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

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

explict   point(anthorPoint  aP)

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

p1 = (point)p2;
原文地址:https://www.cnblogs.com/wlzy/p/5899695.html