继承或对象切片?

时间:2015-11-04 23:17:31

标签: c++ inheritance object-slicing constructor-chaining

我已经对此进行了如此多的阅读,并且无法弄清楚我的Player对象失去其draw功能的原因。

对象类:

class Object {
    public:
        Object(){}

        Object(Object* o){
            o->draw();
        }

        virtual void draw() { cout << "Object draw" << endl; }
};

玩家类:

class Player : public Object {
    public:
        Player() : Object(this) {}

        void draw(){ cout << "Player draw" << endl; }
};

当我运行此代码时:

int main(){
    Object o;
    Player p;
}

输出为:Object draw。我希望它是Player draw所以对象要么没有覆盖,要么对象在通过函数时会被切片。

0 个答案:

没有答案