Cast to a Child

前端 未结 4 1751
无人及你
无人及你 2021-01-23 07:47

What I\'m actually trying to do is cast a constructed moneypunct to the punct_facet in this question without writing a copy constructor as in this answ

4条回答
  •  太阳男子
    2021-01-23 08:32

    It wouldn't work as you think, since you have made the function func virtual. This means that even if you were to convert the pointer to Parent to a pointer to Child, the func() of that object would still be Parent::func().

    Now, you could theoretically do something like this:

    #include 
    
    class Parent
    {
    public:
            virtual void foo() { std::cout << "parent" << std::endl; }
    };
    
    class Child : public Parent
    {
    public:
            virtual void foo() { std::cout << "child" << std::endl; }
    };
    
    int main()
    {
            Child child;
            child.foo(); // "child"
            child.Parent::foo(); // "parent"
            Parent parent;
            parent.foo(); // "parent"
            ((Child*)(&parent))->foo(); // still "parent"
            ((Child*)(&parent))->Child::foo(); // "child"
            return 0;
    }
    

    And while i may receive some downvotes for posting this broken code, i think that it is necessary to show what is happening in this case. You would need to convert both, the pointer to the object, and then specify exactly which function you are intending to call.

    Depending upon what you are doing, it may better be accomplished by using friend classes:

    #include 
    
    class ParentHelper;
    class ChildHelper;
    class Parent
    {
        friend class ParentHelper;
        friend class ChildHelper;
    private:
        int a=5;
    };
    
    class ParentHelper
    {
    public:
        virtual void func(Parent *p)
        {
            std::cout << "parent helper, but i see a " << p->a << std::endl;
        }
    };
    
    class ChildHelper : public ParentHelper
    {
    public:
        virtual void func(Parent *p)
        {
            std::cout << "child helper, but i see a also " << p->a << std::endl;
        }
    };
    
    void foo(Parent* p, ParentHelper *h)
    {
        h->func(p);
    }
    
    int main()
    {
        Parent p;
        ParentHelper ph;
        ChildHelper ch;
    
        ph.func(&p);
        ch.func(&p);
    
        foo(&p, &ph);
        foo(&p, &ch);
    
        return 0;
    }
    

    Note several things:

    1. Friendships are not inherited, so you must then list all children to ParentHelper that you intend to use.
    2. It does, however, give you a way to access all the data members of your Parent class as is, it won't cause some weird behaviour.
    3. This may still not be what you are looking for, but from your question i think that it may help.

提交回复
热议问题