[C++] Type Conversion(类型转换)

Type Conversion(类型转换)

 

Two kinds of type conversion

  • explict type conversion(显式类型转换)

  • impict type conversion(隐式类型转换)

Two way to  convert type

  • 赋值

  • 构造函数

  • 转换函数

转换函数

 

不支持friend

 

类与类转换

 1 #include <iostream>
 2 
 3 class mianji
 4 {
 5 public:
 6     friend class fushu;
 7     mianji()
 8     {
 9         this->cx = 0;
10         this->cy = 0;
11     }
12     void setxy(int a,int b)
13     {
14         this->cx = a;
15         this->cy = b;
16     }
17 protected:
18 private:
19     int cx;
20     int cy;
21 };
22 
23 class fushu
24 {
25 public:
26     friend class mianji;//ÓÑÔª¿ÉÒÔ·ÃÎÊ˽ÓбäÁ¿
27     fushu(mianji mianji1)
28     {
29         this->x = mianji1.cx;
30         this->y = mianji1.cy;
31     }
32     void print()
33     {
34         std::cout << x << "+" << y << "i" << std::endl;
35     }
36     operator mianji()
37     {
38         mianji temp;
39         temp.cx = x;
40         temp.cy = y;
41         return  temp;
42     }
43 
44 protected:
45 private:
46     int x;
47     int y;
48 };
49 
50 void main()
51 {
52     mianji  mianji1;
53     fushu fushu1 =(fushu) mianji1;//通过构造函数转换
54     fushu fushu1(mianji1);//通过构造函数转换
55     
56     mianji  mianji2;
57     mianji2.setxy(10, 20);
58 
59     fushu1 = mianji2;//通过构造函数转换
60     mianji2 = fushu1;//通过转换函数来转换
61     fushu1.print();
62     std::cin.get();
63 }

 

转载于:https://www.cnblogs.com/tianhangzhang/p/4952591.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值