我遇到了这个问题,不知道如何解决。
假设我有这些基类:
class ValueBase
{
private:
int base_value;
public:
int GetValue();
void SetValue(int val);
virtual ValueBase* Meet(ValueBase* const a, ValueBase* const b) = 0;
}
class NodeBase
{
private:
ValueBase* base_nodeValue;
public:
bool AddValue(int val);
}
和派生类:
class Value : public ValueBase
{
public:
Value* Meet(ValueBase* a, ValueBase* b) override;
}
有没有办法在类 NodeBase
的方法 AddValue
中创建类 Value
的实例?我知道我可能应该使 AddValue
纯虚拟并在 NodeBase
的派生类中实现它,但是如果没有这个选项是否有可能做到这一点?我可以使用例如模板方法或者可能是 Value
中构造该对象的方法的回调?还是这样做太邪恶了?
编辑:
我无权访问类 NodeBase
Value
最佳答案
添加创建成员函数:
class ValueBase
{
public:
virtual ValueBase * create() = 0;
// ...
};
然后在NodeBase
中你可以使用base_nodeValue->create()
。
派生类实现它:
class Value : public ValueBase
{
Value * create() override { return new Value; }
};
不过,此模式更常见的形式是克隆 函数,它不会生成相同类型的默认构造对象,而是复制:
Derived * clone() override { return new Derived(*this); }
关于c++ - 在 C++ 中创建派生抽象类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31343225/