我有两个类,如下所示(我尽可能抽象示例):
#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
,需要使用哪些内容?
答案 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