C++ Overridden method not getting called

后端 未结 8 1342
逝去的感伤
逝去的感伤 2021-02-13 11:20

Shape.h

namespace Graphics {
    class Shape {
    public:
        virtual void Render(Point point) {};
    };
}

Rect.h

namespa         


        
8条回答
  •  梦谈多话
    2021-02-13 11:46

    I'm not sure to explain well because of my english is poor.

    I think you should have to use it reference or pointer type. because shape is exactly defined what it has to do.

    If you use your code directly, your child try to copy and do shape's working. That is why doesn't work your override function.

    use pointer or reference like this.

    pointer.h

    class Parent {
    public:
        virtual void work() { printf("parent is working now\n"); }
    };
    class Child1 {
    public:
        virtual void work() { printf("child1 is working now\n"); }
    };
    class Child2 {
    public:
        virtual void work() { printf("child2 is working now\n"); }
    };
    struct Holder {
        Parent* obj1;
        Parent* obj2;
    };
    int main() {
        Child1 child1;
        Child2 child2;
        Holder holder = { &child1, &child2 };
        holder.obj1->work();
        holder.obj2->work();
        return 0;
    }
    

    reference.h

    class Parent {
    public:
        virtual void work() { printf("parent is working now\n"); }
    };
    class Child1 {
    public:
        virtual void work() { printf("child1 is working now\n"); }
    };
    class Child2 {
    public:
        virtual void work() { printf("child2 is working now\n"); }
    };
    struct Holder {
        Parent& obj1;
        Parent& obj2;
    };
    int main() {
        Child1 child1;
        Child2 child2;
        Holder holder = { child1, child2 };
        holder.obj1.work();
        holder.obj2.work();
        return 0;
    }
    

    *ps: personally i use abstract function(virtual void something() = 0;). because i also forgot about it sometimes so i catch it as syntax error.

提交回复
热议问题