c ++从派生类指针获取基类对象?

时间:2011-03-22 04:33:24

标签: c++ derived-class superclass

假设我有Derived * derivedPtr;
我想要来自derivedPtr的Base baseObject;

Base baseObject = * derivedPtr;会使用适当的Base类成员变量创建baseObject吗?

谢谢

3 个答案:

答案 0 :(得分:2)

Object Slicing

Derived* obj = new Derived;
base objOne = (*obj) ;  // Object slicing. Coping only the  Base class sub-object
                        // that was constructed by eariler statement.

答案 1 :(得分:1)

您可以使用动态投射来完成此任务。

e.g。

Base* baseObject = dynamic_cast<Base*>(derivedPtr);

http://www.cplusplus.com/doc/tutorial/typecasting/

答案 2 :(得分:0)

是。这实际上被称为“切片”,因为你只是从派生类中切掉一切。