从基类执行重写方法

时间:2012-11-01 14:04:12

标签: c++ inheritance virtual

我有两个类,如下所示(我尽可能抽象示例):

#include <iostream>
using namespace std;

class foo1
{
public:
    foo1() {};
    virtual ~foo1() {};
    void Method1()           { Method2(); }
    virtual void Method2()   { cout<<"parent";}
};

class foo2 : public foo1
{
public:
    virtual void Method2()  { cout<<"child";}
};

int main()
{
    foo2 a = foo2();
    a.Method1();
}

我收到了“父母”消息。因此Method1() foo2执行foo1::Method2()

为了使foo2::Method1调用foo2::Method2,需要使用哪些内容?

1 个答案:

答案 0 :(得分:9)

不,你没有,你得到"child"。如果你做了

,你会得到父母
foo1 a = foo2();   // My crystal ball tells me this is what you really have

这可能是由于对象切片造成的。要使它工作,你需要指针或引用:

foo2 f;
foo1& rf = f;
rf.Method1();   //child

foo1* a = new foo2();
a->Method1();   //child