本节条款相对简单,通俗的意思就是说 “有一个”和“是一个”的区别,以及在应用域(application domain)和实现域之间的区别(implementation domain)。
如下代码:
1.
class Bird//鸟
{
public:
//............
};
class ostrich:public Bird//鸵鸟
{
public:
//............
};
这段代码是指“是一个”的关系,鸵鸟也是鸟,鸵鸟有鸟的各种属性。
2.
class Name
{
public:
//..............
};
class Person
{
public:
//.......
private:
Name name;
};
这段代码是指“有一个”的关系,名字是一个类,每个人都有一个名字。
3.
再看一下书上的例子:
#include <iostream>
#include <list>
using namespace std;
template <class T>
class MySet
{
private:
list<T> MyList;
public:
int Size() const
{
return MyList.size();
}
bool IsContained(T Element) const
{
return (find(MyList.begin(), MyList.end(), T) != MyList.end());
}
bool Insert(T Element)
{
if (!IsContained(T))
{
MyList.push_back(Element);
return true;
}
else
{
return false;
}
}
bool Remove(T Element)
{
list<T>::iterator Iter = find(MyList.begin(), MyList.end(), T);
if (Iter != MyList.end())
{
MyList.erase(Iter);
return true;
}
else
{
return false;
}
}
};
这是在实现域的体现,我们在编程的时候选取的结构是为我们程序功能服务的,所以我们要改造已有的结构,以适应我们的需求。如上,list结构可能会存储相同的元素,但是set类要求不能存储相同元素,所以为了让list结构为我们的程序服务,我们在程序中限定了list的操作,以达到我们的需求。
时间: 2024-12-24 04:15:48