C++中為什么不要混用繼承層級和數(shù)組

這篇文章主要講解了“C++中為什么不要混用繼承層級和數(shù)組”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“C++中為什么不要混用繼承層級和數(shù)組”吧!

創(chuàng)新互聯(lián)專注于湛河企業(yè)網(wǎng)站建設,響應式網(wǎng)站建設,商城網(wǎng)站建設。湛河網(wǎng)站建設公司,為湛河等地區(qū)提供建站服務。全流程定制網(wǎng)站開發(fā),專業(yè)設計,全程項目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務

T.81:不要混用繼承層級和數(shù)組

Reason(原因)

An array of derived classes can implicitly "decay" to a pointer to a base class with potential disastrous results.

派生類的數(shù)組可以隱式退化為可能帶來災難性后果的指向基類的指針。

Example(示例)

Assume that Apple and Pear are two kinds of Fruits.

假定Apple和Pear是兩種Fruit。

void maul(Fruit* p)
{
   *p = Pear{};     // put a Pear into *p
   p[1] = Pear{};   // put a Pear into p[1]
}

Apple aa [] = { an_apple, another_apple };   // aa contains Apples (obviously!)

maul(aa);
Apple& a0 = &aa[0];   // a Pear?
Apple& a1 = &aa[1];   // a Pear?

Probably, aa[0] will be a Pear (without the use of a cast!). If sizeof(Apple) != sizeof(Pear) the access to aa[1] will not be aligned to the proper start of an object in the array. We have a type violation and possibly (probably) a memory corruption. Never write such code.

很有可能aa[0]是一個Pear(不需要類型轉(zhuǎn)化)。如果sizeof(Apple)!=sizeof(Pear),對于aa[1]的訪問位置就不會正確開始于下個對象。我們會遇到類型違反和可能的(幾乎一定)內(nèi)存破壞。永遠不要這樣寫代碼。

Note that maul() violates the a T* points to an individual object rule.

Alternative: Use a proper (templatized) container:

注意maul()已經(jīng)違反了使用T*或onwer<T*>指明唯一對象原則。其他選項:使用適當?shù)模0寤模┤萜鳌?/p>

void maul2(Fruit* p)
{
   *p = Pear{};   // put a Pear into *p
}

vector<Apple> va = { an_apple, another_apple };   // va contains Apples (obviously!)

maul2(va);       // error: cannot convert a vector<Apple> to a Fruit*
maul2(&va[0]);   // you asked for it

Apple& a0 = &va[0];   // a Pear?

Note that the assignment in maul2() violated the no-slicing rule.

注意maul2()中的賦值操作違反了不要分割對象原則。

Enforcement(實施建議)

  • Detect this horror!

    檢出這種可怕的問題!

感謝各位的閱讀,以上就是“C++中為什么不要混用繼承層級和數(shù)組”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對C++中為什么不要混用繼承層級和數(shù)組這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關知識點的文章,歡迎關注!

當前名稱:C++中為什么不要混用繼承層級和數(shù)組
本文來源:http://muchs.cn/article12/ieppdc.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、全網(wǎng)營銷推廣、品牌網(wǎng)站設計、搜索引擎優(yōu)化外貿(mào)建站、響應式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司