C++指针转换

C++ Pointers Conversion

本文关键字:转换 指针 C++      更新时间:2023-10-16

我是C++编程新手,所以这个问题可能是基本的,但这里是:

我有四个班级 - A,B,C和D。它们的关系定义如下:

class B : public A;
class D : public C;

A 是一个抽象类(所有方法都是纯虚拟的)。类 D 实现了 C 没有的 Print() 函数。

//Class D - some code
void Print()
{
    //some code
}

类 A 有一个 STL::list,其中包含指向类 C 对象的指针。

//Class A - some code
protected:
    list<C*> myObjects;

在类 B 中,我有一个函数,它将 myObjects 指针推送到 D 类型的对象(再次,D 继承 C),该对象运行良好。

Class B : public A
{
    // Some code
    D* obj = new D(...);
    myObjects.push_back(obj);
    return obj;
}

最后,在类 B 中,我有一个遍历 myObjects(继承自类 A)的函数,如下所示:

for(list<C*>::iterator it = myObjects.begin(); it != myObjects.end(); it++)
{
    //I wish to call the function D.Print() but I get an error!
    D *a = *it;
    a->Print();
}

错误状态:

error C2440: 'initializing': cannot convert from 'std::_List_iterator<_Mylist>' to 'D*'

我的印象是,如果"a"是指向类 D 对象的指针,那么如果我给它迭代器引用的指针的值(指向指向 D 类型的对象的指针),我可以调用 Print()。

你能帮忙吗?提前感谢!

如果定义,则无需尝试转换为D类型

virtual void Print() = 0;

在课堂C.

然后你可以通过编写来利用多态性

C *a = *it;
C->Print();

或者,更好的是,

(*it)->Print();

如果你不能做到这一点,那么你可以使用dynamic_cast,或者简单地存储list<D*> myObjects;

试试

D *a=dynamic_cast<D *>(*it)

列表的内容可能是 D 对象,但这仅在运行时已知,因此编译器在编译时无法知道列表是否包含 D 对象或来自 C 的其他派生类。

作为记录,此代码在 ideone 上编译

确保PrintC 中声明为纯虚拟,然后在打印循环中使用C指针而不是D。你不需要任何强制转换,这就是虚函数的用途。