国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C++箴言:謹慎使用多繼承

2019-11-17 05:08:48
字體:
來源:轉載
供稿:網友

  觸及 multiple inheritance (MI)(多繼續)的時候,C++ 社區就會鮮明地分裂為兩個基本的陣營。一個陣營認為假如 single inheritance (SI)(單繼續)是有好處的,multiple inheritance(多繼續)一定更有好處。另一個陣營認為 single inheritance(單繼續)有好處,但是多繼續引起的麻煩使它得不償失。在本文中,我們的主要目的是理解在 MI 問題上的這兩種看法。

  首要的事情之一是要承認當將 MI 引入設計領域時,就有可能從多于一個的 base class(基類)中繼續相同的名字(例如,函數,typedef,等等)。這就為歧義性提供了新的時機。例如:

class BorrowableItem { // something a library lets you borrow
public:
 void checkOut(); // check the item out from the library
 ..
};

class ElectronicGadget {
PRivate:
 bool checkOut() const; // perform self-test, return whether
 ... // test sUCceeds
};

class mp3Player: // note MI here
public BorrowableItem, // (some libraries loan MP3 players)
public ElectronicGadget
{ ... }; // class definition is unimportant

MP3Player mp;

mp.checkOut(); // ambiguous! which checkOut?
  注重這個例子,即使兩個函數中只有一個是可訪問的,對 checkOut 的調用也是有歧義的。(checkOut 在 BorrowableItem 中是 public(公有)的,但在 ElectronicGadget 中是 private(私有)的。)這與 C++ 解析 overloaded functions(重載函數)調用的規則是一致的:在看到一個函數的是否可訪問之前,C++ 首先確定與調用匹配最好的那個函數。只有在確定了 best-match function(最佳匹配函數)之后,才檢查可訪問性。這目前的情況下,兩個 checkOuts 具有相同的匹配程度,所以就不存在最佳匹配。因此永遠也不會檢查到 ElectronicGadget::checkOut 的可訪問性。

  為了消除歧義性,你必須指定哪一個 base class(基類)的函數被調用:

mp.BorrowableItem::checkOut(); // ah, that checkOut...
  當然,你也可以嘗試顯式調用 ElectronicGadget::checkOut,但這樣做會有一個 "you're trying to call a private member function"(你試圖調用一個私有成員函數)錯誤代替歧義性錯誤。

  multiple inheritance(多繼續)僅僅意味著從多于一個的 base class(基類)繼續,但是在還有 higher-level base classes(更高層次基類)的 hierarchies(繼續體系)中出現 MI 也并不罕見。這會導致有時被稱為 "deadly MI diamond"(致命的多繼續菱形)的后果。

class File { ... };
class InputFile: public File { ... };
class OutputFile: public File { ... };
class IOFile: public InputFile,
public OutputFile
{ ... };
 C++箴言:謹慎使用多繼續

  在一個“在一個 base class(基類)和一個 derived class(派生類)之間有多于一條路徑的 inheritance hierarchy(繼續體系)”(就像上面在 File 和 IOFile 之間,有通過 InputFile 和 OutputFile 的兩條路徑)的任何時候,你都必須面對是否需要為每一條路徑復制 base class(基類)中的 data members(數據成員)的問題。例如,假設 File class 有一個 data members(數據成員)fileName。IOFile 中應該有這個 field(字段)的多少個拷貝呢?一方面,它從它的每一個 base classes(基類)繼續一個拷貝,這就暗示 IOFile 應該有兩個 fileName data members(數據成員)。另一方面,簡單的邏輯告訴我們一個 IOFile object(對象)應該僅有一個 file name(文件名),所以通過它的兩個 base classes(基類)繼續來的 fileName field(字段)不應該被復制。

  C++ 在這個爭議上沒有自己的立場。它恰當地支持兩種選項,雖然它的缺省方式是執行復制。假如那不是你想要的,你必須讓這個 class(類)帶有一個 virtual base class(虛擬基類)的數據(也就是 File)。為了做到這一點,你要讓從它直接繼續的所有的 classes(類)使用 virtual inheritance(虛擬繼續):

class File { ... };
class InputFile: virtual public File { ... };
class OutputFile: virtual public File { ... };
class IOFile: public InputFile,
public OutputFile
{ ... };
  標準 C++ 庫包含一個和此類似的 MI hierarchy(繼續體系),只是那個 classes(類)是 class templates(類模板),名字是 basic_ios,basic_istream,basic_ostream 和 basic_iostream,而不是 File,InputFile,OutputFile 和 IOFile。

  從正確行為的觀點看,public inheritance(公有繼續)應該總是 virtual(虛擬)的。假如這是唯一的觀點,規則就變得簡單了:你使用 public inheritance(公有繼續)的任何時候,都使用 virtual public inheritance(虛擬公有繼續)。唉,正確性不是唯一的視角。避免 inherited fields(繼續來的字段)復制需要在編譯器的一部分做一些 behind-the-scenes legerdemain(幕后的戲法),而結果是從使用 virtual inheritance(虛擬繼續)的 classes(類)創建的 objects(對象)通常比不使用 virtual inheritance(虛擬繼續)的要大。訪問 virtual base classes(虛擬基類)中的 data members(數據成員)也比那些 non-virtual base classes(非虛擬基類)中的要慢。編譯器與編譯器之間有一些細節不同,但基本的要點很清楚:virtual inheritance costs(虛擬繼續要付出成本)。

  它也有一些其它方面的成本。支配 initialization of virtual base classes(虛擬基類初始化)的規則比 non-virtual bases(非虛擬基類)的更加復雜而且更不直觀。初始化一個 virtual base(虛擬基)的職責由 hierarchy(繼續體系)中 most derived class(層次最低的派生類)承擔。這個規則中包括的含義:

  (1) 從需要 initialization(初始化)的 virtual bases(虛擬基)派生的 classes(類)必須知道它們的 virtual bases(虛擬基),無論它距離那個 bases(基)有多遠;

  (2) 當一個新的 derived class(派生類)被加入繼續體系時,它必須為它的 virtual bases(虛擬基)(包括直接的和間接的)承擔 initialization responsibilities(初始化職責)。

  我對于 virtual base classes(虛擬基類)(也就是 virtual inheritance(虛擬繼續))的建議很簡單。首先,除非必需,否則不要使用 virtual bases(虛擬基)。缺省情況下,使用 non-virtual inheritance(非虛擬繼續)。第二,假如你必須使用 virtual base classes(虛擬基類),試著避免在其中放置數據。這樣你就不必在意它的 initialization(初始化)(以及它的 turns out(清空),assignment(賦值))規則中的一些怪癖。值得一提的是 java 和 .NET 中的 Interfaces(接口)不答應包含任何數據,它們在很多方面可以和 C++ 中的 virtual base classes(虛擬基類)相比照。

  現在我們使用下面的 C++ Interface class(接口類)(參見《C++箴言:最小化文件之間的編譯依靠》)來為 persons(人)建模:


class IPerson {
public:
 virtual ~IPerson();

 virtual std::string name() const = 0;
 virtual std::string birthDate() const = 0;
};
  IPerson 的客戶只能使用 IPerson 的 pointers(指針)和 references(引用)進行編程,因為 abstract classes(抽象類)不能被實例化。為了創建能被當作 IPerson objects(對象)使用的 objects(對象),IPerson 的客戶使用 factory functions(工廠函數)(再次參見 Item 31)instantiate(實例化)從 IPerson 派生的 concrete classes(具體類):

// factory function to create a Person object from a unique database ID;
// see Item 18 for why the return type isn't a raw pointer
std::tr1::shared_ptr<IPerson> makePerson(DatabaseID personIdentifier);

// function to get a database ID from the user
DatabaseID askUserForDatabaseID();


DatabaseID id(askUserForDatabaseID());
std::tr1::shared_ptr<IPerson> pp(makePerson(id)); // create an object
// supporting the
// IPerson interface

... // manipulate *pp via
// IPerson's member
// functions
  但是 makePerson 怎樣創建它返回的 pointers(指針)所指向的 objects(對象)呢?顯然,必須有一些 makePerson 可以實例化的從 IPerson 派生的 concrete class(具體類)。

  假設這個 class(類)叫做 CPerson。作為一個 concrete class(具體類),CPerson 必須提供它從 IPerson 繼續來的 pure virtual functions(純虛擬函數)的 implementations(實現)。它可以從頭開始寫,但利用包含大多數或全部必需品的現有組件更好一些。例如,假設一個老式的 database-specific class(老式的數據庫專用類)PersonInfo 提供了 CPerson 所需要的基本要素:

class PersonInfo {
public:
 eXPlicit PersonInfo(DatabaseID pid);
 virtual ~PersonInfo();

 virtual const char * theName() const;
 virtual const char * theBirthDate() const;
 ...

private:
 virtual const char * valueDelimOpen() const; // see
 virtual const char * valueDelimClose() const; // below
 ...
};
  你可以看出這是一個老式的 class(類),因為 member functions(成員函數)返回 const char*s 而不是 string objects(對象)。盡管如此,假如鞋子合適,為什么不穿呢?這個 class(類)的 member functions(成員函數)的名字暗示結果很可能會非常合適。

  你忽然發現 PersonInfo 是設計用來幫助以不同的格式打印 database fields(數據庫字段)的,每一個字段的值的開始和結尾通過指定的字符串定界。缺省情況下,字段值開始和結尾定界符是方括號,所以字段值 "Ring-tailed Lemur" 很可能被安排成這種格式:

[Ring-tailed Lemur]
  根據方括號并非滿足 PersonInfo 的全體客戶的期望的事實,virtual functions(虛擬函數)valueDelimOpen 和 valueDelimClose 答應 derived classes(派生類)指定它們自己的開始和結尾定界字符串。PersonInfo 的 member functions(成員函數)的 implementations(實現)調用這些 virtual functions(虛擬函數)在它們返回的值上加上適當的定界符。作為一個例子使用 PersonInfo::theName,代碼如下:

const char * PersonInfo::valueDelimOpen() const
{
 return "["; // default opening delimiter
}

const char * PersonInfo::valueDelimClose() const
{
 return "]"; // default closing delimiter
}

const char * PersonInfo::theName() const
{
 // reserve buffer for return value; because this is
 // static, it's automatically initialized to all zeros
 static char value[Max_Formatted_Field_Value_Length];

 // write opening delimiter
 std::strcpy(value, valueDelimOpen());

 append to the string in value this object's name field (being careful to avoid buffer overruns!)

 // write closing delimiter
 std::strcat(value, valueDelimClose());

 return value;
}
  有人可能會質疑 PersonInfo::theName 的陳舊的設計(非凡是一個 fixed-size static buffer(固定大小靜態緩沖區)的使用,這樣的東西發生 overrun(越界)和 threading(線程)問題是比較普遍的——參見《C++箴言:必須返回對象時別返回引用》),但是請把這樣的問題放到一邊而注重這里:theName 調用 valueDelimOpen 生成它要返回的 string(字符串)的開始定界符,然后它生成名字值本身,然后它調用 valueDelimClose。

  因為 valueDelimOpen 和 valueDelimClose 是 virtual functions(虛擬函數),theName 返回的結果不僅依靠于 PersonInfo,也依靠于從 PersonInfo 派生的 classes(類)。

  對于 CPerson 的實現者,這是好消息,因為當細讀 IPerson documentation(文檔)中的 fine print(晦澀的條文)時,你發現 name 和 birthDate 需要返回未經修飾的值,也就是,不答應有定界符。換句話說,假如一個人的名字叫 Homer,對那個人的 name 函數的一次調用應該返回 "Homer",而不是 "[Homer]"。

  CPerson 和 PersonInfo 之間的關系是 PersonInfo 碰巧有一些函數使得 CPerson 更輕易實現。這就是全部。因而它們的關系就是 is-implemented-in-terms-of,而我們知道有兩種方法可以表現這一點:經由 composition(復合)(參見《C++箴言:通過composition模擬“has-a”》)和經由 private inheritance(私有繼續)(參見《C++箴言:謹慎使用私有繼續》)。《C++箴言:謹慎使用私有繼續》指出 composition(復合)是通常的首選方法,但假如 virtual functions(虛擬函數)要被重定義,inheritance(繼續)就是必不可少的。在當前情況下,CPerson 需要重定義 valueDelimOpen 和 valueDelimClose,所以簡單的 composition(復合)做不到。最直截了當的解決方案是讓 CPerson 從 PersonInfo privately inherit(私有繼續),雖然 《C++箴言:謹慎使用私有繼續》說過只要多做一點工作,則 CPerson 也能用 composition(復合)和 inheritance(繼續)的組合有效地重定義 PersonInfo 的 virtuals(虛擬函數)。這里,我們用 private inheritance(私有繼續)。

  但是 CPerson 還必須實現 IPerson interface(接口),而這被稱為 public inheritance(公有繼續)。這就引出一個 multiple inheritance(多繼續)的合理應用:組合 public inheritance of an interface(一個接口的公有繼續)和 private inheritance of an implementation(一個實現的私有繼續):


class IPerson { // this class specifies the
public: // interface to be implemented
 virtual ~IPerson();

 virtual std::string name() const = 0;
 virtual std::string birthDate() const = 0;
};

class DatabaseID { ... }; // used below; details are
// unimportant

class PersonInfo { // this class has functions
public: // useful in implementing
 explicit PersonInfo(DatabaseID pid); // the IPerson interface
 virtual ~PersonInfo();

 virtual const char * theName() const;
 virtual const char * theBirthDate() const;

 virtual const char * valueDelimOpen() const;
 virtual const char * valueDelimClose() const;
 ...
};

class CPerson: public IPerson, private PersonInfo { // note use of MI
public:
 explicit CPerson( DatabaseID pid): PersonInfo(pid) {}
 virtual std::string name() const // implementations
 { return PersonInfo::theName(); } // of the required
 // IPerson member
 virtual std::string birthDate() const // functions
 { return PersonInfo::theBirthDate(); }
private: // redefinitions of
 const char * valueDelimOpen() const { return ""; } // inherited virtual
 const char * valueDelimClose() const { return ""; } // delimiter
}; // functions
  在 UML 中,這個設計看起來像這樣:

C++箴言:謹慎使用多繼續

  這個例子證實 MI 既是有用的,也是可理解的。

  時至今日,multiple inheritance(多繼續)不過是 object-oriented toolbox(面向對象工具箱)里的又一種工具而已,典型情況下,它的使用和理解更加復雜,所以假如你得到一個或多或少等同于一個 MI 設計的 SI 設計,則 SI 設計總是更加可取。假如你能拿出來的僅有的設計包含 MI,你應該更加專心地考慮一下——總會有一些方法使得 SI 也能做到。但同時,MI 有時是最清楚的,最易于維護的,最合理的完成工作的方法。在這種情況下,毫不畏懼地使用它。只是要確保謹慎地使用它。

  Things to Remember

  ·multiple inheritance(多繼續)比 single inheritance(單繼續)更復雜。它能導致新的歧義問題和對 virtual inheritance(虛擬繼續)的需要。

  ·virtual inheritance(虛擬繼續)增加了 size(大小)和 speed(速度)成本,以及 initialization(初始化)和 assignment(賦值)的復雜度。當 virtual base classes(虛擬基類)沒有數據時它是最適用的。

  ·multiple inheritance(多繼續)有合理的用途。一種方案涉及組合從一個 Interface class(接口類)的 public inheritance(公有繼續)和從一個有助于實現的 class(類)的 private inheritance(私有繼續)。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 壶关县| 班玛县| 石嘴山市| 五常市| 邻水| 分宜县| 华容县| 平阳县| 大兴区| 南郑县| 全南县| 贵港市| 孟连| 穆棱市| 全椒县| 南安市| 通河县| 达州市| 福清市| 友谊县| 开封县| 金坛市| 巩义市| 城市| 浮梁县| 惠水县| 嘉定区| 福建省| 翁牛特旗| 昌宁县| 永泰县| 漳浦县| 台前县| 云安县| 江油市| 吴川市| 吉安县| 贵溪市| 广宁县| 莎车县| 武义县|