題目要求
定義一個集合類String,處理整形數組,通過成員函數重載運算符判斷一個數是否屬於一個函數,通過友元重載運算服判斷兩個集合是否相同,集合中的所有元素相同,但順序可不同
(1) 私有數據成員
int* a; 數據成員存放整形數組集合爲數組中的所有元素
int len; 數據成員數組的長度
(2) 公有成員函數
SET(int* p, int n); 構造函數與形參初始化數據成員
int operator ==(int m); 重載函數判斷m是否屬於當前對象所屬的集合
friend int operator ==(SET& s1, SET& s2); 重載函數判斷s1和s2所屬的集合是否相同
void print(); 輸出集合函數
~SET(); 釋放動態內存
(3)對定義的類進行測試,以集合爲測試數據判斷是否相同
輸出
a: 1 2 3 4 5
b: 1 2 3 4 5
c: 1 2 3 4 5 6
d: 1 3 5 7 9
a==b
a!=c
a!=d
代碼展示.
#include<iostream>
#include <iomanip>
using namespace std;
class SET
{
private:
int* a;
int len;
public:
SET(int* p, int n);
int operator ==(int m);
friend int operator ==(SET& s1, SET& s2);
void print();
~SET();
};
SET::SET(int* p, int n)
{
a = p;
len = n;
}
int SET::operator ==(int m)
{
for (int i = 0; i < len; i++)
{
if (*a == m)
return 1;
a++;
}
return 0;
}
int operator ==(SET& s1, SET& s2)
{
int* b = s2.a,i,j;
if (s1.len != s2.len)
{
return 0;
}
for (i = 0; i < s1.len; i++)
{
for (j = 0; j < s1.len; j++)
{
if (*s1.a == *s2.a)
*s2.a = -1;
s2.a++;
}
s1.a++;
s2.a=b;
}
s2.a=b;
int flag = 1;
for (i = 0; i < s2.len; i++)
{
if (*b!= -1)
flag = 0;
b++;
}
return flag;
}
void SET::print()
{
int i;
int* b=a;
for (i = 0; i < len; i++)
{
cout << setw(4) << *b;
b++;
}
cout << endl;
}
SET::~SET()
{
delete[] a;
}
int main()
{
int a[5] = { 1,2,3,4,5 }, b[5] = { 1,2,3,4,5};
int c[6] = { 1,2,3,4,5,6 }, d[6] = { 1,3,5,7,9 };
SET A(a, 5), B(b, 5), C(c, 6), D(d, 5);
cout << "a:";
A.print();
cout << "b:";
B.print();
cout << "c:";
C.print();
cout << "d:";
D.print();
if (operator ==(A, B))
cout << "a==b" << endl;
else
cout << "a!=b" << endl;
if (operator ==(A, C))
cout << "a==c" << endl;
else
cout << "a!=c" << endl;
if (operator ==(A, D))
cout << "a==d" << endl;
else
cout << "a!=d" << endl;
return 0;
}