第七章

【7.11】

为Date类重载“+”运算符,实现在某一日期上(月日年)加一个天数。

include<iostream>    
using namespace std;
class Date{
      public:
	    Date(){ }
       Date(int i)  
	   {day=i; }
          
	    Date(int m,int d,int y)
	    { month=m;
        day=d;
       year=y; 
      }
	    void print()
	    { cout<<year<<"."<<month<<"."<<day<<endl;
	    }
 
Date operator+(Date& a)  
{   day=day+a.day;  
	return (*this);  }
private:
	 int month,day,year;
};

int main()
{ Date d1(7,2,1996),d2;
      d1.print();
      d2=d1+Date(1);
      d2.print();
system("pause");  
	  return 0;
}

【7.10】

用友元函数重载运算符“+”和“-”将两人维数组相加减

#include<iostream>    
#include <iomanip>
using namespace std;
const int row=2; const int col=3;
class array {
public:
        array();                              
	    array(int a,int b,int c,int d,int e,int f);
        void get_array( );                   
void display();                       
friend array operator+(array &X,array &Y);  
friend array operator-(array &X,array &Y);  
private:
int var[row][col];
};

    array::array()
{ for (int i=0; i<row; i++)
        for (int j=0;j<col; j++)
          var[i][j]=0;  
}
array::array(int a,int b,int c,int d,int e,int f)
{                                      
	  var[0][0]=a; var[0][1]=b; var[0][2]=c;
	  var[1][0]=d; var[1][1]=e; var[1][2]=f;	}
      void  array::get_array( )              
      { cout<<" Please input 2*3 dimension data: "<<endl;
	    for (int i=0; i<row; i++)
	      for (int j=0;j<col; j++)
	        cin>>var[i][j];   
}
      void  array::display()                  
      { for (int i=0; i<row;i++)
	    { for (int j=0;j<col;j++ )
	        cout<<setw(5)<< var[i][j];
	        cout<<endl;  
}
      }
array operator+(array &X,array &Y)       
    { array temp;
for (int i=0;i<row; i++)
	    for (int j=0;j<col;j++)
	      temp.var[i][j]=Y.var[i][j]+X.var[i][j];
	  return temp;
}
array operator-(array &X,array &Y)        
{ array temp;
	  for (int i=0; i<row; i++)
	    for (int j=0; j<col; j++ )
	      temp.var[i][j]=X.var[i][j]-Y.var[i][j];
	  return temp ;
    }
int main()
{ array X(12,15,16,18,20,21);
      array Y,Z;
      Y.get_array();
      cout<<"Display object X"<<endl; 
	  X.display();
      cout<<"Display object Y"<<endl; 
	  Y.display();
      Z=X+Y;
      cout<<" Display object Z=X+Y"<<endl; 
	  Z.display();
      Z=X-Y;
      cout<<" Display object Z=X-Y"<<endl;
	  Z.display(); 
	   system("pause");
      return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值