试题描述
定义集合Gather类,编写必要的构造函数,且重载加法运算符函数(实现集合并运算)、减法运算符函数(实现集合差运算)、输出运算符友元函数。请仔细阅读下面的代码,并填写空白。
相关阅读
c++|类改错B
c++|继承改错B
c++|典型运算符重载之集合类填空
c++|虚基类之构造函数填空
c++|类静态成员之英雄类
c++|纯虚函数之再谈星际争霸
① //必要的头文件等,可能为多条语句
② //定义类Gather
{
protected:
int m_data[100]; //数据成员
int m_count; //集合元素个数
③
④ //定义默认构造函数,函数体中调用Clear()函数
⑤ //清空集合函数Clear(),函数体中设置m_count为0
⑥ //定义返回集合元素个数函数int GetCount(),函数体中返回m_count
⑦ //定义集合元素位置函数int Find(),函数只有一个参数,即要查找的元素值。元素位置从0开始,找不到则返回-1。
⑧ //定义加入集合元素函数Add(),函数只有一个参数,即要加入集合的元素值。如果该元素在集合中已经存在,则返回false;否则加入该元素,并返回true。
⑨ //定义移出集合元素函数Remove(),函数只有一个参数,即要移出集合的元素值。如果该元素在集合中不存在,则返回false;否则移出该元素,并返回true。
⑩ //重载加号运算符,代表集合并运算,函数只有一个参数,即Gather类型集合g2对象的常引用。
⑪ //重载减法运算符,代表集合差运算,函数只有一个参数,即Gather类型集合g2对象的常引用。
⑫ //输出运算符<<重载友元函数,函数有两个参数,即ostream类型dout的引用、Gather类型集合g对象的常引用。
};
int main()
{
⑬ //创建Gather对象g1和g2
int x, y, a, b;
⑭ //输入整数x和y,然后将[x, y]之间的所有整数放入集合g1中
⑮ //调用默认赋值运算符重载函数,将g1赋给g2
cout << "集合g2内容如下:" << g2 << endl; //调用输出运算符重载函数
⑯ //调用默认拷贝构造函数,将g1赋给g3
cin >> x >> y >> a >> b;
⑰ //从g3中移走集合元素函数x,y
⑱ //加入a和b到集合g3中
cout << "集合g3内容如下:" << g3 << endl;
cout << "集合g2与g3的差:" << g2 - g3 << endl;
cout << "集合g2与g3的合:" << g2 + g3 << endl;
return 0;
}
注意:1.请务必提交完整的程序代码,不要修改代码框架。2.请不要修改试题描述中的所有标识符,注意大小写敏感。
输入
输入六个整数,相邻两项之间用一个空格隔开。
输出
依据题意输出若干行。
输入示例
1 5 2 4 6 7
输出示例
集合g2内容如下:(1,2,3,4,5)
集合g3内容如下:(1,3,5,6,7)
集合g2与g3的差:(2,4)
集合g2与g3的合:(1,2,3,4,5,6,7)
数据范围
输入为int范围的整数
#include <iostream>
#include <algorithm>
using namespace std;
class Gather
{
protected:
int m_data[100];
int m_count;
public:
Gather(){
Clear();
}
void Clear(){
m_count = 0;
}
int GetCount(){
return m_count;
}
int Find(int x){
for(int i = 0; i < m_count; i++){
if(m_data[i] == x)
return i;
}
return -1;
}
bool Add(int x){
if(Find(x)!=-1)
return false;
m_data[m_count++] = x;
return true;
}
bool Remove(int x){
if(Find(x)==-1)
return false;
for(int i = Find(x); i < m_count-1; i++){
m_data[i] = m_data[i+1];
}
m_count--;
return true;
}
Gather operator+(const Gather &g2){
Gather temp = *this;
for(int i = 0; i < g2.m_count; i++){
temp.Add(g2.m_data[i]);
}
return temp;
}
Gather operator-(const Gather &g2){
Gather temp = *this;
for(int i = 0; i < g2.m_count; i++){
temp.Remove(g2.m_data[i]);
}
return temp;
}
friend ostream& operator << (ostream &dout, const Gather &g);
};
ostream& operator << (ostream &dout, const Gather &g){
dout << "(" ;
for(int i = 0; i < g.m_count; i++){
if(i!=g.m_count-1)
dout << g.m_data[i] << ",";
else
dout << g.m_data[i];
}
dout << ")" ;
return dout;
}
int main(){
Gather g1, g2;
int x,y,a,b;
cin >> x >> y;
for(int i = x; i<= y; i++){
g1.Add(i);
}
g2=g1;
cout << "集合g2内容如下:" << g2 << endl;
Gather g3=g1;
cin >> x >> y >> a >> b;
g3.Remove(x);
g3.Remove(y);
g3.Add(a);
g3.Add(b);
cout << "集合g3内容如下:" << g3 << endl;
cout << "集合g2与g3的差:" << g2 - g3 << endl;
cout << "集合g2与g3的合:" << g2 + g3 << endl;
return 0;
}