我有点惊讶以下代码没有按预期工作:
#include "stdio.h"
class RetA
{
public:
virtual void PrintMe () { printf ("Return class A\n"); }
};
class A
{
public:
virtual RetA GetValue () { return RetA (); }
};
class RetB : public RetA
{
public:
virtual void PrintMe () { printf ("Return class B\n"); }
};
class B : public A
{
public:
virtual RetA GetValue () { return RetB (); }
};
int main (int argc, char *argv[])
{
A instance_A;
B instance_B;
RetA ret;
printf ("Test instance A: ");
ret = instance_A.GetValue ();
ret.PrintMe (); // Expected result: "Return class A"
printf ("Test instance B: ");
ret = instance_B.GetValue ();
ret.PrintMe (); // Expected result: "Return class B"
return 0;
}
那么,虚拟方法在返回值时不起作用吗?我应该恢复在堆上分配返回类,还是有更好的方法?
(实际上我想这样做是为了让一些从容器类继承的不同类根据类返回不同的迭代器类实例......)