return a Type, or how to preserve a type of an object pointer?

前端 未结 3 1838
不知归路
不知归路 2021-01-20 13:34

I have a very complicated code structure, but the important bits are:

typical setup: I have a base class and two classes that derive from this base class and each ha

3条回答
  •  旧巷少年郎
    2021-01-20 14:23

    Use dynamic_cast to try to cast a pointer-to-base-class to pointer-to-derived-class. It will return NULL if the pointed-to object of the base class does not exist (NULL value of the base pointer), or is not actually a derived class object. If the result, instead, is not NULL, you have a valid pointer-to-derived-class.

    int main(){
        IOService ioService;
        BaseSolver* mySolver = ioService.getSolver();
        SolverB* bSolver = dynamic_cast(mySolver);
        if (bSolver != NULL)
        {
            int finallyIGotB = bSolver->b;
            cout << finallyIGotB;
        }
    }
    

    Note that there may be some better design solutions than using dynamic_cast. But at least this is one possibility.

提交回复
热议问题