c++ - C ++将子子类转换为基类
问题描述
使用以下课程:
enum class OBJECT_TYPE {TYPE_1, TYPE_2, TYPE_3};
class BaseClass {
public:
BaseClass();
virtual ~BaseClass();
OBJECT_TYPE getObjectType() { return m_objectType; }
protected:
OBJECT_TYPE m_objectType;
}
class ChildClass : public BaseClass {
public:
ChildClass();
virtual ~ChildClass();
virtual void init() = 0;
protected:
// some other variables
}
class ChildChildClass : public ChildClass {
public:
ChildChildClass ();
~ChildChildClass ();
void init() override { m_objectType = OBJECT_TYPE::TYPE_3 }
private:
// some other variables
}
在代码库的单独部分中,我将如何将 avoid*
转换为ChildChildClass
实例,BaseClass*
以便我可以调用getObjectType()
以确定它指向的对象类型。我目前正在这样做:
(someOtherMethod()
返回 avoid*
到 a ChildChildClass
)
void* initialPointer = someOtherMethod();
BaseClass* basePointer = static_cast<BaseClass>(initialPointer);
if (basePointer->getObjectType() == OBJECT_TYPE::TYPE_3) {
ChildChildClass* childChildPointer = static_cast<ChildChildClass*>(basePointer);
}
我想我在使用继承时可能会误解转换指针,因为我得到的返回值是无意义的,objectType
所以任何建议或信息都将不胜感激!
解决方案
我将忽略这种设计的众多问题,并假设您有充分的理由(即无法更改设计)想要做您所要求的事情。如果您知道someOtherMethod()
返回的 avoid*
指向一个ChildChildClass
对象,那么您可以先将static_cast
其返回void*
到 a ChildChildClass*
,然后执行显式向上转换为 aBaseClass*
或仅将其ChildChildClass*
用作 a BaseClass*
,因为它无论如何都可以隐式转换(应该不需要执行upcast 只是为了调用该方法,因为ChildChildClass
公开派生自BaseClass
):
ChildChildClass* initialPointer = static_cast<ChildChildClass*>(someOtherMethod());
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);
但是,根据您上面的代码,我相信您实际上并不知道someOtherMethod()
返回指向ChildChildClass
对象的指针。否则,为什么要在强制转换之前检查它是否有效ChildChildClass*
?如果您不知道void*
返回的对象的具体类型someOtherMethod()
,则无法在此处执行您想要执行的转换(因为有知道什么应该实际转换为什么的方法)。一种解决方案是更改someOtherMethod()
为始终返回一个BaseClass*
或至少返回一个void*
您肯定知道始终指向一个BaseClass
对象的...
推荐阅读
- html - 为什么我使用margin时还有margin: 0; 在那个元素上
- laravel - 调度程序未运行 Laravel 5
- pandas - 从文件名导入多个 csv 时创建日期索引
- javascript - 如何在 JavaScript 中检查表格的单元格索引
- redux - 使用 react redux 恢复 Ag Grid 的列状态
- typescript - TypeScript 在函数中自动捕获数组类型变量
- heroku - Heroku 如何使用 AWS S3 凭证访问我存储桶中的图像?
- python - Python PIP 抛出错误 - ImportError: cannot import name main
- msdeploy - MSdeploy 仅适用于根目录的跳过规则
- python - 使用线程类时 Tkinter 应用程序冻结