C++指针转换
C++ Pointers Conversion
我是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 上编译
确保Print
在 C
中声明为纯虚拟,然后在打印循环中使用C
指针而不是D
。你不需要任何强制转换,这就是虚函数的用途。
相关文章:
- 转换指针引用的字符串
- 无法向上转换指针到指针参数
- 混合转换指针和引用
- 堆栈对象的强制转换指针
- 基类到派生模板类的强制转换指针,而不知道类型
- 删除类型转换指针的最佳方法
- 管理到本机值类转换:强制转换指针是否安全?
- 转换指针类型
- 为什么函数不能正确强制转换指针(从基类到派生类)
- 当我们递增下面的类型转换指针时会发生什么?
- 类型强制转换指针构造函数调用
- 如何转换(指针向量)-->(指向指针数组的指针)
- 如何从类功能转换指针
- 在C++对象中:我应该使用父类强制转换指针,还是应该使用实际类本身进行强制转换
- Delphi中的类型转换指针添加
- C++分段错误(核心转储)错误 - 强制转换指针/将函数值返回到线程
- 以C++和运算符优先级键入指向数组成员的强制转换指针
- C++动态强制转换指针的内存清理
- 转换指针和引用的好处
- 在c++中转换指针