类型转换函数
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