类型转换
1 /* 类型转换 */
2
3 /* 转换方式 */
4
5 #include<iostream>
6 using namespace std;
7
8 int main()
9 {
10 int a = 3/2;// 隐式转换
11
12 double b = (int)5.6// 显式转换
13
14 double c = static_cast<int>()3.5;// C++显式转换
15
16 // b c 先进行显式转换明确类型,赋值号进行隐式转换
17
18 cin.get();
19 return 0;
20 }
21
22 //----------------------------------------------------
23
24 /* 基本数据类型与自定义类型转换 */
25
26 #include<iostream>
27 using namespace std;
28
29 class myclass
30 {
31 public:
32 int x;
33 int y;
34 myclass(int num)
35 {
36 cout << "create" << endl;
37 x = y = num;
38 }
39
40 void operator =(int num)
41 {
42 cout << "operator = " << endl;
43 x = y = num;
44 }
45
46 };
47
48 int main()
49 {
50 myclass my1;
51 //my1 = 5;// 调用了构造函数初始化
52
53 my1 = 7;// 如果没有赋值重载 默认调用构造 有赋值重载就调用赋值重载
54
55 cout << my1.x << " " << my1.y << endl;
56
57 cin.get();
58 return 0;
59 }
60
61
62 //----------------------------------------------------
63
64
65 /* 基本数据类型与类类型重载类型的转换 */
66
67 #include<iostream>
68 using namespace std;
69
70 class myclass
71 {
72 public:
73 int x;
74 int y;
75 operator int()// 重载int 可以实现本类型转换为int
76 {
77 return (x+y)/2;
78 }
79
80 //---------------------------------------
81 operator double()// double 返回类型
82 {
83 return (x+y)/2.0;// 返回的数据
84 }
85 //---------------------------------------
86
87 operator double();// 声明不需要声明属于哪个类就在类的内部
88 // 只能是类成员函数 不可能是友元或者外部函数
89
90
91 };
92
93 myclass::operator double()// double 返回类型,强调属于哪个类,没有返回类型 没有参数
94 {
95 return (x+y)/2.0;// 返回的数据
96 }
97
98
99 int main()
100 {
101 myclass my1;
102 my1.x = 12;
103 my1.y = 18;
104
105 int num = my1;
106
107 cout << num << endl;
108
109 double db = my1;
110
111 cout << db << endl;
112
113 cin.get();
114 return 0;
115 }
116
117
118 //----------------------------------------------------
119
120 int main()
121 {
122 myclass my1;
123 my1.x = 12;
124 my1.y = 18;
125
126 int a = my1;// 隐式转换
127
128 int a = (int)my1;// 显式转换
129
130 int a = int(my1);// 显式转换
131
132 int a = static_cast<int>(my1);// CPP风格显式转换
133
134 cout << a << endl;
135
136 cin.get();
137 return 0;
138 }
长风破浪会有时,直挂云帆济沧海
posted on 2015-06-07 09:55 Dragon-wuxl 阅读(72) 评论(0) 收藏 举报
浙公网安备 33010602011771号