7.10

来源:互联网 发布:怎样用java做网站 编辑:程序博客网 时间:2024/06/06 04:32
#include<iostream.h>  #include<iomanip.h>const int r=2;  const int c=3;class A {        public: A();                          //构造函数     A(int a,int b,int c,int d,int e,int f); void get_A( );            //键盘输入数组的值        void show();               //显示数组     friend A operator+(A &X,A &Y);    //相加 friend A operator-(A &X,A &Y);    //相减 private: int m[r][c]; };  A::A() { for(int i=0; i<r; i++)        for(int j=0;j<c; j++)          m[i][j]=0;   } A::A(int a,int b,int c,int d,int e,int f) {                                 //由构造函数设置数组的值    m[0][0]=a;  m[0][1]=b;  m[0][2]=c;    m[1][0]=d;  m[1][1]=e;  m[1][2]=f;  } void  A::get_A( )        //键盘输入数组的值    { cout<<"Please input 2*3 data:"<<endl;    for (int i=0; i<r; i++)     for (int j=0;j<c; j++)       cin>>m[i][j];   } void  A::show()          //显示数组   { for (int i=0; i<r;i++)     { for (int j=0;j<c;j++ )        cout<<setw(5)<<m[i][j];       cout<<endl;   } } A operator+(A &X,A &Y)    //相加      { A temp;     for (int i=0;i<r; i++)          for(int j=0;j<c;j++) temp.m[i][j]=Y.m[i][j]+X.m[i][j];           return temp;     } A operator-(A &X,A &Y)    //相减     { A temp; for (int i=0; i<r; i++)      for (int j=0; j<c; j++ ) temp.m[i][j]=X.m[i][j]-Y.m[i][j];        return temp;      } int main(){ A X(6,7,8,9,10,11);      A Y,Z;       Y.get_A(); cout<<"X:"<<endl;   X.show();     cout<<"Y:"<<endl;   Y.show();       Z=X+Y;     cout<<"X+Y:"<<endl;       Z.show();      Z=X-Y;     cout<<"X-Y:"<<endl;  Z.show();        return 0; } 


注意:因Visual C++6.0没有完全实现C++标准,它所提供的不带后缀的.h的头文件不支持吧运算符函数重载为友元函数,在Visual C++6.0中编译会出错,这是需要把头文件部分写成: #include<iostream.h>     #include <iomanip.h>,并把using namespace std;去掉。这时就可以顺利运行了。

(摘自书本188页) 

0 0