如何在派生类上强制派生类成员 [英] How to enforce derived class members on derived classes

查看:124
本文介绍了如何在派生类上强制派生类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何强制派生类具有特定派生类型的成员数据.

How does one enforce a derived class to have member data of a specific derived type.

class Project {
  public:
    int projdata;
};

class Article: public Project {
};

class Building: public Project {
};

class Emplooyee {
  public:
    std::vector<Project> projs;
}

class Architect: public Employee {
};

class Writer: public Employee {
};

我现在如何强制Architect对象仅具有Building类型的项目,而Novelist仅具有Article类型的项目?即,我想要类似的东西

How do I now enforce that Architect objects only have projects of type Building, while Novelist only have projects of type Article? i.e., I want to have something like

class Architect: public Employee {
  public:
    std::vector<Building> projs;
};

class Novelist: public Employee {
  public:
    std::vector<Article> projs;
};

我还可以存储指向项目的指针,然后将其转换为正确的类型.是否有一种技术或设计模式可以在派生类的成员上强制执行此类相应的继承规则?

I could also store pointers to projects and then store cast them into the correct type. Is there a technique or design pattern to enforce such corresponding inheritance rules on members of derived classes?

推荐答案

一种编译时的解决方案是使基础成为模板:

A compile time solution is to make the base a template:

template<class Proj>
class Emplooyee {
  public:
    std::vector<Proj> projs;
}

class Architect: public Employee<Building> {};

class Writer: public Employee<Article> {};

此外,您可以添加一个其他的非模板库,以使ArchitectWriter属于同一层次结构,但是该非模板库不能处理projs成员.

Additionally, you can add a one additional non-template base so that Architect and Writer are part of same hierarchy, but that non-template base cannot deal with the projs member.

如果模板不是选项,则必须依靠运行时检查.为此,Project必须是多态类型,并且必须使用typeiddynamic_cast来强制不变量.并且您必须首先使用间接存储Project. std::vector<Project>无法存储任何BuildingArticle对象,因为它仅存储Project个对象

If a template not an option, then you must rely on runtime checks. For that, Project must be a polymorphic type, and you must use typeid or dynamic_cast, to enforce the invariant. And you must use indirection to store the Project's in the first place. std::vector<Project> cannot store any Building nor Article objects because it only stores Project objects only

这篇关于如何在派生类上强制派生类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆