gpt4 book ai didi

c++ - 是否可以根据需要继续向基类(接口(interface))添加虚方法?

转载 作者:行者123 更新时间:2023-11-27 22:44:13 26 4
gpt4 key购买 nike

让我们考虑以下 OOP 结构。基类(接口(interface))是所谓的“节点”类。另外两个类继承自'Node',即'ElementNode'、'TextNode'。我需要使用多态容器 (vector>)。在某些时候,我需要从通过 vector 提取的元素中获取一些类成员,该元素被向上转换隐藏,例如来自“TextNode”的文本。我的问题是,在设计方面,是否可以继续向基类“Node”添加虚拟方法以获得对隐藏成员的访问权限。另一种选择是使用向下类型转换。设计有缺陷吗?如果有缺陷,您会建议什么替代方案?

C++ 示例代码:

class Node {
public:
Node() {};
virtual ~Node() {};

NodeTypes getNodeType() const { return nodeType; };
virtual std::vector<std::shared_ptr<Node>> &getChildren() = 0;
virtual void pushChild(std::shared_ptr<Node>) = 0;

private:
NodeTypes nodeType;
std::vector<std::shared_ptr<Node>> children;
};

class ElementNode : public Node {
public:
ElementNode(HtmlElements, Node*);

void setTag(HtmlElements);

//Inherited methods.
std::vector<std::shared_ptr<Node>> &getChildren();
void pushChild(std::shared_ptr<Node>);
Node* getFather() const;
};

class TextNode : public Node {
public:
TextNode(std::string);
std::string getText() const;
void setText(std::string);

//Inherited methods.
std::vector<std::shared_ptr<Node>> &getChildren();
void pushChild(std::shared_ptr<Node>);
Node* getFather() const;

private:
std::string text;
};

最佳答案

“按需”添加方法最终会与 Interface Segregation Principle 冲突固体。

并非所有 Node 客户端都需要了解所有变体,对吧?这意味着当您的基类变得臃肿时,客户将被迫了解所有细节。这听起来很像 Robert Martin 在 ISP 定义中给出的施乐打印机示例。

getText() 添加到基类意味着您将违反 Liskov Substitution Principle SOLID,因为某些节点不支持该方法。

您的问题是如何识别存储在 vector 中的节点类型。我会说你应该根据 Liskov 替换原则重新考虑你的设计部分。向下转换可能会导致两害相权取其轻。

关于c++ - 是否可以根据需要继续向基类(接口(interface))添加虚方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45085204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com