转换函数

将person类转为double

 1 class Person
 2 {
 3 public:
 4     Person(int a = 0, int b = 0) :m_a(a), m_b(b) {}
 5     operator double()const   //告诉编译器person类可以转为double
 6     {
 7         return (double)m_a /(double) m_b;
 8     }
 9     int m_a;
10     int m_b;
11 };
12 int main()
13 {
14     Person p(3,5);
15     double f = 4 + p;  //将Person转成double
16     std::cout << "f=" << f << std::endl;            //4.6
17 }

 有转出函数就有转入函数,即将其他类型的数据转为person类型,以下例子将int转为person

 1 class Person
 2 {
 3 public:
 4     Person() = default;
 5     Person(int a, int b = 1) :m_a(a), m_b(b) {}  //non-explict 允许编译器“暗度陈仓”
 6     Person operator+(const Person &p)
 7     {
 8         Person temp;
 9         temp.m_a = this->m_a + p.m_a;
10         temp.m_b = this->m_b + p.m_b;
11         return temp;
12     }
13     int m_a;
14     int m_b;
15 };
16 int main()
17 {
18     Person p1(20, 4);
19     Person p2 = p1 + 5;  //发生类型转换,然后调用operator+
20     cout << p2.m_a << "," << p2.m_b << endl;  //25    5
21 
22 }

如果在5行前面加explicit关键字,不让编译器帮我们做隐式转换,那么19行就编译不过。