如果你正在开发一个具有多媒体功能的通讯录程序。这个通讯录除了能存储通常的文字信息如姓名、地址、电话号码外,还能存储照片和声音(可以给出他们名字的正确发音)。
为了实现这个通信录,你可以这样设计:
class Image { // 用于图像数据 public: Image(const string& imageDataFileName); ... };
class AudioClip { // 用于声音数据 public: AudioClip(const string& audioDataFileName); ... };
class PhoneNumber { ... }; // 用于存储电话号码 class BookEntry { // 通讯录中的条目 public: BookEntry(const string& name, const string& address = "", const string& imageFileName = "", const string& audioClipFileName = ""); ~BookEntry(); // 通过这个函数加入电话号码 void addPhoneNumber(const PhoneNumber& number); ... private: string theName; // 人的姓名 string theAddress; // 他们的地址 list thePhones; // 他的电话号码 Image *theImage; // 他们的图像 AudioClip *theAudioClip; // 他们的一段声音片段 }; |
通讯录的每个条目都有姓名数据,所以你需要带有参数的构造函数(参见条款3),不过其它内容(地址、图像和声音的文件名)都是可选的。注意应该使用链表类(list)存储电话号码,这个类是标准C++类库(STL)中的一个容器类(container classes)。(参见Effective C++条款49 和本书条款35)
编写BookEntry 构造函数和析构函数,有一个简单的方法是:
BookEntry::BookEntry(const string& name,const string& address, const string& imageFileName, Const string& audioClipFileName) : theName(name), theAddress(address), theImage(0), theAudioClip(0) { if (imageFileName != "") { theImage = new Image(imageFileName); } if (audioClipFileName != "") { theAudioClip = new AudioClip(audioClipFileName); } } BookEntry::~BookEntry() { delete theImage; delete theAudioClip; } |
构造函数把指针theImage和theAudioClip初始化为空,然后如果其对应的构造函数参数不是空,就让这些指针指向真实的对象。析构函数负责删除这些指针,确保BookEntry对象不会发生资源泄漏。因为C++确保删除空指针是安全的,所以BookEntry的析构函数在删除指针前不需要检测这些指针是否指向了某些对象。
看上去好像一切良好,在正常情况下确实不错,但是在非正常情况下(例如在有异常发生的情况下)它们恐怕就不会良好了。www.goodsgy.com
www.goodsgy.com [1] [2] [3] [4] [5] 下一页
|