c++ cc24a_demo //转换函数,用来做转换操作符,int()括号里面必须是空的,必须定义为const,代码示范
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 class Dog 6 { 7 public: 8 Dog(string n, int a, double w) :name(n), age(a), weight(w) {} 9 operator int() const//转换函数,用来做转化操作符,int()括号里面必须是空的,必须定义为const 10 { 11 return age; 12 } 13 operator double() const//转换函数 14 { 15 return weight; 16 } 17 operator std::string() const//转换函数 18 { 19 return name; 20 } 21 private: 22 int age; 23 double weight; 24 string name; 25 }; 26 27 int main() 28 { 29 int a, b; 30 a = 10; 31 b = a; 32 Dog d("Bill",6,15.0); 33 b = d; //d得到的是整形,调用转换函数,operator int() 34 cout << b << endl; 35 36 getchar(); 37 return 0; 38 }