整数集合运算(重载)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Fiverya/article/details/88863065

编写一个程序,通过重载运算符"+"、"-",实现一个整数集合的基本运算:
(1) int1+int2  两个整数集合的并运算
(2) int1-int2  两个整数集合的差运算
输入:5      
     2 5 66 1 79
     3
     2 66 28
结果:int1+int2=2 5 66 1 79 28
       int1-int2=5 1 79
注:第1、3行数为集合元素个数,第2、4行为集合中各个元素

#include<iostream>  
using namespace std;  
class Integer  
{     
    public:  
    int a,b[10];  
    void getint() {cin>>a; for(int i=0;i<a;i++) cin>>b[i];}  
    void show();  
    friend Integer operator+(Integer &c1,Integer &c2);  
    friend Integer operator-(Integer &c1,Integer &c2);  
};        
Integer operator+(Integer &c1,Integer &c2)  
{  
    int i,j;  
    for(i=0;i<c2.a;i++)  
    {  
        for(j=0;j<c1.a;j++)  
        {   if(c2.b[i]==c1.b[j]) break;  
            else if(j==c1.a-1)   
            {c1.b[c1.a]=c2.b[i];c1.a++;}  
        }     
    }  
    return c1;  
}  
Integer operator-(Integer &c1,Integer &c2)  
{  
    int i,j;  
    for(i=0;i<c2.a;i++)  
    {  
        for(j=0;j<c1.a;j++)  
        {   if(c2.b[i]==c1.b[j])  
                {for(int m=j;m<c1.a;m++)  
                    c1.b[m]=c1.b[m+1];  
                    c1.a--;  
                }  
        }     
    }  
    return c1;  
}  
void Integer::show()  
    {  if(a!=0)   
        {cout<<b[0];  
            for(int i=1;i<a;i++)  
            cout<<' '<<b[i];  
        }  
        cout<<endl;  
    }  
int main()  
{  
    Integer c1,c2,c3,c4;  
    c1.getint();  
    c2.getint();  
    c3=c1+c2;  
    c4=c1-c2;  
    cout<<"int1+int2=";  
    c3.show();  
    cout<<"int1-int2=";  
    c4.show();  
    return 0;  
} 

猜你喜欢

转载自blog.csdn.net/Fiverya/article/details/88863065