2014-11-06 65 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

相关问题