Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 不知道在完成a<;之后我上了什么类型的课;动态铸造>;_C++_Dynamic Cast - Fatal编程技术网

C++ 不知道在完成a<;之后我上了什么类型的课;动态铸造>;

C++ 不知道在完成a<;之后我上了什么类型的课;动态铸造>;,c++,dynamic-cast,C++,Dynamic Cast,我有这样的结构: class IIterator : public ICollectible{}; class A: public ICollectible{}; class b: public A{}; class c: public A{}; class d: public A{}; 当我这样做的时候 IIterator* it = colection->getIterator(); whatType* db = dynamic_cast<whatType*>(it-&g

我有这样的结构:

class IIterator : public ICollectible{};
class A: public ICollectible{};
class b: public A{};
class c: public A{};
class d: public A{};
当我这样做的时候

IIterator* it = colection->getIterator();
whatType* db = dynamic_cast<whatType*>(it->hasCurrent());
IIterator*it=collection->getIterator();
whatType*db=dynamic_cast(it->hasCurrent());
collection是包含
A
类型元素的列表(它可以包含
b
c
d
类型的对象)
hasCurrent()
给了我一些类型ICollectible的东西,所以我不得不这么做

动态演员阵容,让我可以工作
使用
b
c
d
,但我如何知道它是哪一个呢?

动态强制转换的要点是,它会告诉您是否有正确的类型,或者返回null ptr。因此,您可以:

if (b *p = dynamic_cast<b *>(it->hasCurrent())) {
    // its b
} else if (c *p = dynamic_cast<c *>(it->hasCurrent())) {
    // its c
} else if (d *p = dynamic_cast<d *>(it->hasCurrent())) {
    // its d
} else {
    // none of the above
if(b*p=dynamic\u cast(it->hasCurrent()){
//是b
}如果(c*p=dynamic_cast(it->hasCurrent()){
//它是c
}否则如果(d*p=dynamic\u cast(it->hasCurrent()){
//它是d
}否则{
//以上都没有

当然,许多OO纯粹主义者会认为这是“坏代码气味”。--您应该在接口类中定义一个虚拟函数并调用它,而不是测试不同的派生类型。

如果您需要知道类型的真实类型,混合类型有什么意义?欢迎使用Stack Overflow。请花时间阅读并参考“What and how”中的资料。我想ep 3 A类物品的不同列表?我当时正在做,但看起来太可怕了,以为还有另一个way@MarcosAyala另一种方法是使用多态性。通过
std::function
、虚拟分派甚至函数指针。