假设我有以下内容:

class A { virtual void g() = 0 }

class B : public A { virtual void g() { ... } }
class C : public A { virtual void g() { ... } }

... f(bool x)
{
  if (x) { return B(); } else { return C(); }
}

bool get_boolean();

int main()
{
  bool b = get_boolean();
  ... x = f(b);
  x.g();
}

无论如何,是否可以在不调用 new 的情况下执行上述操作,即仅在堆栈上?

最佳答案

在函数 f 对象 B()C() 都是临时的,所以你只能从 f 按值返回它们。

也许 boost::variant 适合你。然后你甚至不需要让方法虚拟或从公共(public)基类派生。

关于c++ - 没有 "new"的多态性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13340664/

10-11 22:36
查看更多