Access child members within parent class, C++

后端 未结 9 907
南方客
南方客 2020-12-09 06:16

I am facing a situation where I need to access child member variables inside the parent class. I know this is against OO principles but I have to deal with a scenario where

9条回答
  •  我在风中等你
    2020-12-09 06:29

    If you're allowed to change your child classes source code, you can do something like that:

    class Parent
    {
    public:
        void DoSomething()
        {
            getMember() = 0;
        }
        virtual int & getMember() = 0;
    };
    
    class Child1 : public Parent
    {
        int childMember;
    public:
        int & getMember()
        {
            return childMember;
        }
    };
    
    class Child2 : public Parent
    {
        int childMember;
    public:
        int & getMember()
        {
            return childMember;
        }
    };
    

    Otherwise, if your object has virtual table (at least one virtual method), you can use static_cast() in combination with C++11 typeid, because it's about three times faster than dynamic_cast:

    #include 
    
    class Parent
    {
    public:
        virtual void DoSomething();
    };
    
    class Child1 : public Parent
    {
    public:
        int childMember;
    };
    
    class Child2 : public Parent
    {
    public:
        int childMember;
    };
    
    void Parent::DoSomething()
    {
        if (typeid(Child1) == typeid(*this))
        {
            auto child = static_cast(this);
            child->childMember = 0;
        }
        else if (typeid(Child2) == typeid(*this))
        {
            auto child = static_cast(this);
            child->childMember = 0;
        }
    };
    

提交回复
热议问题