C++语言程序设计

在类外定义的成员函数也称为类的实现，Set类的实现如下：

| 例10-8-b

bool Set::Member (const int elem)
{
for (register i = 0; i < card; ++i)
if (elems[i] == elem)
return true;
return false;
}

void Set::AddElem (const int elem)
{
if (Member(elem))
return;
if (card < maxCard)
elems[card++] = elem;
else
cout << "Set overflow\n";
}

void Set::RmvElem (const int elem)
{
for (register i = 0; i < card; ++i)
if (elems[i] == elem) {
for (; i < card-1; ++i) // shift elements left
elems[i] = elems[i+1];
--card;
}
}
void Set::Copy (Set &set)
{
for (register i = 0; i < card; ++i)
set.elems[i] = elems[i];
set.card = card;
}

bool Set::Equal (Set &set)
{
if (card != set.card)
return false;
for (register i = 0; i < card; ++i)
if (!set.Member(elems[i]))
return false;
return true;
}

void Set::Intersect (Set &set, Set &res)
{
res.card = 0;
for (register i = 0; i < card; ++i)
if (set.Member(elems[i]))
res.elems[res.card++] = elems[i];
}

void Set::Union (Set &set, Set &res)
{
set.Copy(res);
for (register i = 0; i < card; ++i)
res.AddElem(elems[i]);
}

void Set::Print (void)
{
cout << "{";
for (int i = 0; i < card-1; ++i)
cout << elems[i] << ",";
if (card > 0) // no comma after the last element
cout << elems[card-1];
cout << "}\n";
}