如何正确实现抽象类的向量



我正在实现一个玩具SQL数据库。在我的代码中,我希望有一个抽象类Field及其两个派生类IntFieldStringField。另外,我想要一个Tuple类,它表示字段的元组。当然,我需要在Tuple类中有一些字段容器,这就是我的代码目前的样子:

// This is an abstract class, but the methods here are irrelevant
class Field {
virtual Type GetType() = 0;
}
// This is a concrete implementation of Field
class IntField : Field {
Type GetType() override { <some code> }
}
// This is another concrete impl of Field
class StringField: Field {
Type GetType() override { <some code> }
}
// This class represents a tuple of Fields
class Tuple {
private:
std::vector<std::shared_ptr<Field>> fields;
public:
// Don't bother in this example that i can be out of range
std::shared_ptr<Field> GetField(int i) { return fields[i]; }
void SetField(int i, std::shared_ptr<Field> f) {
fields[i] = f;
}
}

我知道我不能有std::vector<Field>,因为Field类不能实例化,所以我需要使用智能指针。让我困扰的是字段的获取和设置是如何处理的。能用更好的方法做到这一点吗?

要回答问题的标题:不能有抽象类的向量。

std::vector要求所有实体都是可复制或可分配的。由于不能实例化抽象类的对象,因此不能拥有抽象类型的向量。

但是,可以有一个指向抽象类的指针向量。

示例:

std::vector<Field *> pointers_to_fields;
StringField sf;
IntField integer_field;
pointers_to_fields.push_back(&sf);
pointers_to_fields.push_back(&integer_field);

最新更新