本文介紹了如何檢查對象的類型是否是 C++ 中的特定子類?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在考慮使用 typeid()
但我不知道如何詢問該類型是否是另一個類的子類(順便說一下,它是抽象的)
I was thinking along the lines of using typeid()
but I don't know how to ask if that type is a subclass of another class (which, by the way, is abstract)
推薦答案
你真的不應(yīng)該.如果您的程序需要知道一個對象是什么類,這通常表明存在設(shè)計缺陷.看看你是否可以使用虛函數(shù)獲得你想要的行為.此外,有關(guān)您正在嘗試執(zhí)行的操作的更多信息會有所幫助.
You really shouldn't. If your program needs to know what class an object is, that usually indicates a design flaw. See if you can get the behavior you want using virtual functions. Also, more information about what you are trying to do would help.
我假設(shè)你有這樣的情況:
I am assuming you have a situation like this:
class Base;
class A : public Base {...};
class B : public Base {...};
void foo(Base *p)
{
if(/* p is A */) /* do X */
else /* do Y */
}
如果這是你所擁有的,那么嘗試做這樣的事情:
If this is what you have, then try to do something like this:
class Base
{
virtual void bar() = 0;
};
class A : public Base
{
void bar() {/* do X *
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!