Conversation function

通过conversation function可以把类转成任意类型的值

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Age
 6 {
 7 private:
 8     int _age;
 9 public:
10     Age(int age) : _age(age) {}
11     operator int() const { return _age; }
12     operator string() const { return to_string(_age); }
13 };
14 
15 int main()
16 {
17     Age myAge(35);
18     Age yourAge(21);
19     if ((myAge - yourAge) > 0) {
20         cout << "i am older than you" << endl;
21     }
22     else {
23         cout << "i am younger than you" << endl;
24     }
25 
26     cout << "I am " << myAge << " years old" << endl;
27     return 0;
28 }
jingyg@jingyg:~/share/mytest/cpp_test$ g++ -std=c++11 test.cpp 
jingyg@jingyg:~/share/mytest/cpp_test$ ./a.out 
i am older than you
I am 35 years old

 

posted @ 2017-05-16 15:36  Kjing  阅读(266)  评论(0编辑  收藏  举报