笔试中常出现的虚函数问题

#include <iostream>
#include <cstdio>

struct A {
    void foo() { printf("foo"); }

    virtual void bar() { printf("bar"); }

    A() { bar(); }
};

struct B : A {
    void foo() { printf("b_foo"); }

    void bar() { printf("b_bar"); }
};

int main() {
    A *p = new B;
    p->foo();
    p->bar();
    B b;
    b.foo();
    return 0;
}

执行结果:
barfoob_barbarb_foo

posted @ 2017-08-22 10:07  镜子里的人  阅读(140)  评论(0编辑  收藏  举报