我不确定问题标题是否准确...让我先解释一下我最初的简单场景,然后继续解释我想做什么,但不能做什么。
最初,我有类似的东西:
class Operand;
Operand genOperandA() { ...; return Operand(); }
Operand genOperandB() { ...; return Operand(); }
... // more operand-generation functions
typedef Operand (*OpGen)();
// Table of function pointers
static const OpGen generators[] =
{
genOperandA,
genOperandB,
...
};
// Function to do some operation on the operand
void operate(Operand& op);
...
// Example call
operate(generators[1]());
到目前为止一切顺利(我认为)。但是,现在有几种派生的操作数类型,例如类 RegisterOperand:公共(public)操作数
。我有新的专用 genOperand
函数,理想情况下会返回派生类型的实例。但我不能这样做:
Operand genOperandC() { ...; return RegisterOperand(); }
我不能这样做:
RegisterOperand genOperandC() { ...; return RegisterOperand(); }
static const OpGen generators[] =
{
...
genOperandC,
};
但是,我知道如果我要返回引用或指针类型,这会起作用,所以我目前唯一的选择是:
Operand *genOperandC() { ...; return new RegisterOperand(); }
现在需要显式清理,而这原本是不必要的。
有没有我没有考虑过的替代方案?
最佳答案
你可以换行:
class Operand
{
public:
private:
std::unique_ptr<OperandImpl> mImpl;
};
这类似于策略模式:实际的操作数行为是隐藏的,并且可以通过非虚拟接口(interface)访问。用户得到一份Operand
,她不需要了解它的内部就可以使用它,你可以自由地实现各种派生行为。
关于c++ - 按值传递的返回类型多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3082995/