c++ 运算符重载

设计和实现整型集合类(Set),成员函数要求如下:

1.添加构造函数完成初始化

2.能添加一个元素,元素不重复

3.能删除一个元素

4.输出所有元素

5.求两个集合对象的交集

6.求两个集合对象的并集

7.求两个集合对象的差集

现在,我们改造Set类,重载+(并集)、(-)差集、*(交集)、<<(输出)、>>(输入)和函数调用操作符(添加一个元素)

相关理论知识

  • 在类中重载操作符时,必须被重载为非静态成员函数或友元函数;

  • 用成员函数重载运算符需要的参数的个数总比它的操作数的数少一个,用友元函数重载运算符需要的参数个数与操作数的个数一样多;

  • 插入和提取运算符只能重载为友元函数,函数调用运算符只能重载为成员函数;

改造后的代码如下:

#include <iostream>
using namespace std;
class Set{
    public:
        Set(){num=0;} 
        int find(int x);
        void print();
        int operator () (int x); //调用操作符添加 () 
        friend Set operator + (Set t1,Set t2); //并集 +
        friend Set operator - (Set t1,Set t2); //差集 -
        friend Set operator * (Set t1,Set t2); //交集 *
        friend istream& operator >>(istream& in,Set& t); //输入 >>
        friend ostream& operator >>(ostream& out,Set& t); //输出 <<
    protected:
        int a[100];
        int num;
};
int Set::find(int x){           
        for(int i=0;i<num;i++)
            if(a[i]==x)
                return i;
        return -1;    
}
void Set::print(){
    for(int i=0;i<num;i++)
        cout<<a[i]<<" ";
}
int Set::operator () (int x){          //添加 
    if(find(x)==-1){
        a[num]=x;
        num++;
    }
}
Set operator + (Set t1,Set t2){       //并集
        for(int i=0;i<t2.num;i++)
            t1(t2.a[i]);
        return t1;
}
Set operator * (Set t1,Set t2){       //交集 
        Set temp;
        for(int i=0;i<t1.num;i++){
            for(int j=0;j<t2.num;j++){
                if(t1.a[i]==t2.a[j]) 
                    temp(t1.a[i]);    
            }
        }
        return temp; 
}
Set operator - (Set t1,Set t2){        //差集 
        Set count;
        int i,j,flag;
        for(i=0;i<t2.num;i++)
            t1(t2.a[i]);
        for(i=0;i<t1.num;i++){
            flag=0;
            for(j=0;j<t2.num;j++){
                if(t1.a[i]==t2.a[j])
                    flag=1;
            }
            if(flag==0)
                count(t1.a[i]);
        }
        return count; 
}
istream& operator >>(istream& in,Set& t){
    int i,n,m;
    cout<<"集合元素个数为:";
    cin>>n; 
    cout<<"输入元素为:"; 
    for(i=0;i<n;i++){
        cin>>m;
        t(m);
    }
    return in;
}
ostream& operator <<(ostream& out,Set& t){            //输出 
    t.print() ;
    return out;    
}
int main()
{
    Set s1,s2,s3;
    cin>>s1>>s2;
    cout<<"集合s1:"<<s1<<endl;
    cout<<"集合s2:"<<s2<<endl;
    cout<<"交集:"<<endl;
    s3=s1*s2;
    cout<<"s3:"<<s3<<endl;
    cout<<"并集:"<<endl;    
    s3=s1+s2;
    cout<<"s3:"<<s3<<endl;
    cout<<"差集:"<<endl; 
    s3=s1-s2;
    cout<<"s3:"<<s3<<endl;
    return 0;
}

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值