2014-11-06 67 views
0

我有一個接口MuInterface(抽象類)。和我有3類,從該接口得到:我可以命名從接口派生的每個類嗎?

class A : public MyInterface //... 
class B : public MyInterface //... 
class C : public MyInterface //... 

我有接口的載體:std::vector< std::shared_ptr<MyInterface> > theVec;包含A類型,BC的對象。是否有可能知道在for循環中遍歷該向量以顯示當前對象的類型(如果它是ABC)?我想過像靜態字符串成員,但如何「虛擬化」它?如果我使用顯示靜態const字符串的虛擬函數,可以嗎:

virtual const std::string getType() { return classType; } // classType is static const std::string defined for each class 

+8

是的,但使用接口的關鍵在於將實際類型抽象出來。你爲什麼需要這樣做? – 2014-11-06 09:52:06

+1

如果您需要某種類型的識別,您可能需要考慮CRTP – 2014-11-06 09:53:12

+0

@LuchianGrigore我只是在調試模式下才需要它,以查看該訂單是否正常,但我已驗證它並且沒有問題。我會把展示的東西放在A,B和C類中。我認爲這種方式更好。謝謝 – sop 2014-11-06 10:36:25

回答

3

正如Luchian指出的,接口的目的通常是發出一個「契約」,不管類型如何,都應該履行:只要你提供接口的功能,你就全部設置好了。

不知道爲什麼你需要它,但你可以強制類型識別通過請求提供getType樣功能(這確實是可能的

class MyInterface { 
public: 
    virtual const std::string identify() = 0; 
}; 

class A : public MyInterface { 
public: 
    const std::string identify() { 
     return std::string("A"); 
    } 
}; 

// ... the same for B and C ... 

int main() { 
    std::vector<std::shared_ptr<MyInterface>> theVec; 
    theVec.push_back(std::make_shared<A>()); 
    theVec.push_back(std::make_shared<B>()); 
    theVec.push_back(std::make_shared<C>()); 

    std::cout << theVec[0]->identify(); 
    std::cout << theVec[1]->identify(); 
    std::cout << theVec[2]->identify(); 
} 

Example

另一個更被扭曲的解決方案可能是用CRTP模式專門化您的方法,但我認爲在這種情況下這將是矯枉過正的。

+1

如果只是爲了調試一個快速的'typeid',我想也可以。 – 2014-11-06 10:19:25

+0

@JasonC是的,雖然可能會有一些demangling inbetween。 – 2014-11-06 10:29:49

相關問題