首页 > 其他 > 详细

运算符重载之转换函数

时间:2021-05-12 14:27:45      阅读:11      评论:0      收藏:0      [点我收藏+]

转换函数

将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行就编译不过。

 

运算符重载之转换函数

原文:https://www.cnblogs.com/xiaoxiaolinux/p/14752258.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!