首页 > 解决方案 > 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所以任何建议或信息都将不胜感激!

标签: c++multiple-inheritance

解决方案


我将忽略这种设计的众多问题,并假设您有充分的理由(即无法更改设计)想要做您所要求的事情。如果您知道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对象的...


推荐阅读