其他分享
首页 > 其他分享> > 类和对象-运算符重载

类和对象-运算符重载

作者:互联网

运算符重载

运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

4.5.1 加号运算符重载

作用:实现两个自定义数据类型相加的运算

 

 

成员函数加法重载运算

 1 #include <iostream>
 2 using namespace std;
 3 int a = 10;
 4 int b = 10;
 5 int c = a + b;
 6 class person
 7 {
 8 public:
 9     int m_a;
10     int m_b;
11     person operator+ (person& p)
12     {
13         person tempt;
14         tempt.m_a = m_a + p.m_a;
15         tempt.m_b = m_b + p.m_b;
16         return tempt;
17     }
18 };
19 int main()
20 {
21     person p1;
22     p1.m_a = 10;
23     p1.m_b = 10;
24     person p2;
25     p2.m_a = 10;
26     p2.m_b = 10;
27     person p3 = p1 + p2; //本质上是 :p1.operaor+(p2)
28 cout <<"p1.m_a +p2.m_a = " << p3.m_a << endl 29 << "p1.m_b +p2.m_b = " << p3.m_b << endl; 30 }

 

 全局函数加法重载运算

 1 #include <iostream>
 2 using namespace std;
 3 int a = 10;
 4 int b = 10;
 5 int c = a + b;
 6 class person
 7 {
 8 public:
 9     int m_a;
10     int m_b;
11 };
12 person operator+ (person& p1, person& p2)
13 {
14     person tempt;
15     tempt.m_a = p1.m_a + p2.m_a;
16     tempt.m_b = p1.m_b + p2.m_b;
17     return tempt;
18 }
19 int main()
20 {
21     person p1;
22     p1.m_a = 10;
23     p1.m_b = 10;
24     person p2;
25     p2.m_a = 10;
26     p2.m_b = 10;
27     person p3 = p1 + p2 ;//本质上是operator+(p1,p2)
28 cout <<"p1.m_a +p2.m_a = " << p3.m_a << endl 29 << "p1.m_b +p2.m_b = " << p3.m_b << endl; 30 }

 

 运算符的函数重载

 1 #include <iostream>
 2 using namespace std;
 3 int a = 10;
 4 int b = 10;
 5 int c = a + b;
 6 class person
 7 {
 8 public:
 9     int m_a;
10     int m_b;
11 };
12 person operator+ (person& p1, int num )
13 {
14     person tempt;
15     tempt.m_a = p1.m_a + num ;
16     tempt.m_b = p1.m_b + num;
17     return tempt;
18 }
19 int main()
20 {
21     person p1;
22     p1.m_a = 10;
23     p1.m_b = 10;
24     person p3 = p1 + 10;
25     cout <<"p1.m_a +num = "  << p3.m_a << endl
26         << "p1.m_b +num = " << p3.m_b << endl;
27 }

 

 

总结1:对于内置的数据类型(比如int类型)的表达式的的运算符是不可能改变的

总结2:不要滥用运算符重载(比如加法写成减法等等,会让人看不懂)

标签:p2,10,p1,person,int,运算符,对象,tempt,重载
来源: https://www.cnblogs.com/zaiyewujiang/p/16651656.html