[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 }