| 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 Image *theImage; // 他们的图像 AudioClip *theAudioClip; // 他们的一段声音片段 }; |
| 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; } |
| if (audioClipFileName != "") { theAudioClip = new AudioClip(audioClipFileName); } |
| void testBookEntryClass() { BookEntry b("Addison-Wesley Publishing Company","One Jacob Way, Reading, MA 01867"); ... } |
| void testBookEntryClass() { BookEntry *pb = 0; try { pb = new BookEntry("Addison-Wesley Publishing Company","One Jacob Way, Reading, MA 01867"); ... } catch (...) { // 捕获所有异常 delete pb; // 删除pb,当抛出异常时 throw; // 传递异常给调用者 } delete pb; // 正常删除pb } |