一个程序,让你理解运算符重载操作

时间:2022-05-05
本文章向大家介绍一个程序,让你理解运算符重载操作,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 1 //实现运算符重载
 2 #include<iostream>
 3 #include<cstdio>
 4 using namespace std;
 5 namespace gong
 6 {
 7     const int maxn=2;
 8 }
 9 namespace Var
10 {
11     int i,j;
12 }
13 class Matrix
14 {
15   public :
16      Matrix(){};
17     ~Matrix(){};
18  int array[gong::maxn][gong::maxn];
19  Matrix operator + (const Matrix & aa) const ; //实现函数a+b重载,类外定义
20  Matrix operator - (const Matrix &aa ) const   //实现函数a-b重载
21  {
22      Matrix dd;
23      using namespace gong ;
24      using Var::i;
25      using Var::j;
26      for( i=0;i<maxn;i++)
27      {
28          for( j=0;j<maxn;j++)
29          {
30           dd.array[i][j]=array[i][j]-aa.array[i][j];
31          }
32      }
33      return dd;
34  }
35   /*注意《《,》》这样的运算符不能定义为类重载函数
36    虽然不能“重载”为成员函数,但是可以定义为新的成员函数,只不过使用习惯和常例不符而已。
37  */
38  ostream operator<< (ostream &out) const 
39  {
40      using namespace gong ;
41      using namespace Var;
42      for(i=0;i<maxn ;i++)
43      {
44       for(j=0;j<maxn;j++)
45       {
46        out<<array[i][j]<<ends;
47       }
48        out<<endl;
49       }
50       return out ;
51   }
52 };
53 Matrix Matrix::operator +(const Matrix & aa) const
54 {
55      Matrix dd;
56      using namespace gong ;
57      using namespace Var  ;
58      for( i=0;i<maxn;i++)
59      {
60          for( j=0;j<maxn;j++)
61          {
62            dd.array[i][j]=array[i][j]+aa.array[i][j];
63          }
64      }
65      return dd;
66 }
67 int main()
68 {
69   Matrix a,b,c;
70   using gong::maxn;
71   using namespace Var;
72   for(i=0;i<maxn;i++)
73   {
74       for(j=0;j<maxn;j++)
75       {
76         scanf("%d%d",&a.array[i][j],&b.array[i][j]);
77       }
78   }
79   c=a+b;
80 //  cout<<c<<endl;
81   c<<cout;
82   c=a-b;
83   c<<cout ;
84   return 0;
85 }

不妨设 a[2][2]=                       b[2][2]=

                     { 1, 2                           { 1, 2

                      3 ,4}                              3 ,4}

   在vc上运算的结果为: