本文介紹了派生類和基類之間指針到指針的轉(zhuǎn)換?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
關(guān)于以下 C++ 程序:
Regarding the following C++ program:
class Base { };
class Child : public Base { };
int main()
{
// Normal: using child as base is allowed
Child *c = new Child();
Base *b = c;
// Double pointers: apparently can't use Child** as Base**
Child **cc = &c;
Base **bb = cc;
return 0;
}
GCC 在最后的賦值語句上產(chǎn)生以下錯誤:
GCC produces the following error on the last assignment statement:
error: invalid conversion from ‘Child**’ to ‘Base**’
我的問題分為兩部分:
- 為什么沒有從 Child** 到 Base** 的隱式轉(zhuǎn)換?
- 我可以使用 C 樣式轉(zhuǎn)換或
reinterpret_cast
使這個示例工作.使用這些強(qiáng)制轉(zhuǎn)換意味著拋棄所有類型安全.有什么我可以添加到類定義中以使這些指針隱式轉(zhuǎn)換的,或者至少以一種允許我使用static_cast
的方式來表達(dá)轉(zhuǎn)換?
- Why is there no implicit conversion from Child** to Base**?
- I can make this example work with a C-style cast or a
reinterpret_cast
. Using these casts means throwing away all type safety. Is there anything I can add to the class definitions to make these pointers cast implicitly, or at least phrase the conversion in a way that allows me to usestatic_cast
instead?
推薦答案
如果允許,你可以這樣寫:
If this was allowed, you could write this:
*bb = new Base;
而且c
最終會指向Base
的一個實例.不好.
And c
would end up pointing to an instance of Base
. Bad.
這篇關(guān)于派生類和基類之間指針到指針的轉(zhuǎn)換?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!