C++函数之运算符重载(三)

C++函数之运算符重载(三)

集合类的举例分析

#include<iostream>
using namespace std;
//集合类
class setType
{ public:
setType( unsigned e=128 ); //构造函数
setType( const setType & B ); //复制构造函数
~setType(); //析构函数
setType operator+= ( unsigned x ); //重载+=,把元素x并入集合
setType operator= ( setType B ); //重载=,集合变量赋值
setType operator() (unsigned x=0); //重载(),集合置元素x,默认置空
setType operator+ ( setType B ); //重载+,求并集
setType operator* ( setType B ); //重载*,求交集
setType operator- ( setType B ); //重载-,求差集
bool operator<= ( setType B ); //重载<=,判集合蕴含
//重载!运算符,判空集。集合空返回false,否则返回true
bool operator ! ();
//重载<,判元素属于集合
friend bool operator< ( unsigned x, setType A );
//重载>>,输入集合元素
friend istream & operator>> ( istream &input, setType &A );
//重载<<,输出集合的全部元素
friend ostream & operator<< ( ostream &output, setType &A );
private:
unsigned *set; //建立动态数组指针
unsigned n; //数组长度
unsigned e; //全集元素个数
};
//test.cpp
#include"setTypeHead.h"
int main()
{ setType setA, setB, setC; unsigned x;
cout << "Input the elements of setA, 1-128, until input 0 :\n";
cin >> setA; //输入setA的元素
cout << "Input the elements of setB, 1-128, until input 0 :\n";
cin >> setB; //输入setB的元素
cout << "setA = " << setA << endl; //输出setA的元素
cout << "setB = "<<setB << endl; //输出setB的元素
cout << "Input x: "; cin >> x;
setA += x; //把元素x并入setA
cout << "Put " << x << " in setA = " << setA << endl;
setC = setA + setB; //求并集
cout << "setC = setA+setB = " << setC << endl;
setC = setA * setB; //求交集
cout << "setC = setA*setB = " << setC << endl;
setC = setA - setB; //求差集
cout << “setC = setA-setB = ” << setC << endl;
//判断setA是否蕴含于setB
if( setA <= setB ) cout << "setA <= setB\n";
else cout << "not setA <= setB\n";
cout << "Input x: "; cin >> x;
//判断元素x是否属于setA
if( x < setA ) cout << x << " in " << setA << "\n";
else cout << x << " not in " << setA << "\n";
setC = setA + setB + setC; //多个集合变量运算
cout << "setC = setA+setB+setC = " << setC << endl;
setC(); //置setC为空集
cout<<"setC = " << setC << endl;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值