Java教程

类和对象-运算符重载

本文主要是介绍类和对象-运算符重载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

运算符重载

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

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:不要滥用运算符重载(比如加法写成减法等等,会让人看不懂)

这篇关于类和对象-运算符重载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!