类型转换函数

谁都会走 提交于 2019-12-05 01:00:59

C++中存在将类对象转换成其他类型

语法:

operator type(){}  //无参数无返回值,type类型就是类对象将要转换成的类型

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class test{
 5 int mvalue;
 6 public:
 7         test(int i){
 8                 mvalue = i;
 9         }
10         int value(){
11                 return mvalue;
12         }
13         operator int(){
14                 return mvalue;//类型转换函数(必定无参数)
15         }
16 
17 
18 };
19 int main(){
20         test t(29);
21         int i = t;
22         cout << "i=" << i << endl;//29
23         return 0;
24 }
25 //结果
26 29

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!